天天看點

【python】list 的用法

定義及初始化生成list對象

shoplist = []

或者

shoplist = ['apple','mango','banana','carrot']

從list中取出對象,類似其他開發語言中的數組用法用listname[index],代表從前開始取第index個對象(第一個從0開始記),不同的是多了一種用負數取對象listname[-index],代表從後開始取第index個對象(第一個從-1開始記)

>>> shoplist[0]

'apple'

>>> shoplist[-1]

'carrot'

其實負數 a取法可以換算為:listname[len(listname) + a]

從list中截取部分對象生成新list:listname[fromindex:toindex]代表取出索引從fromindex到toindex,但不包括toindex的元素,這個也叫做list的分片

shoplist[0:2]取出從0開始到第2個元素但不包括shoplist[2],是以結果就相當于取出了shoplist[0]和shoplist[1]組合成的新list

結果為['a','b']

‘:’兩邊的值可以省略,前面省略代表0,後面省略代表list長度

shoplist[0:2]相當于shoplist[:2]

>>> shoplist[2:]

['banana', 'carrot']

>>> shoplist[1:3] 

['mango', 'banana']

向list添加對象有3種方法

1)向list後面添加一個對象:listname.append(obj)

例:

>>> shoplist.append('meat')

>>> shoplist

['apple', 'mango', 'banana', 'carrot', 'meat']

2)向list中間指定索引位置插入一個對象:listname.insert(index,obj)

>>> shoplist.insert(3,'rice')

['apple', 'mango', 'banana', 'rice', 'carrot', 'meat']

3)向list中添加一個list中的多個對象,相當于兩個list相加:listname.extend(listname2)

>>> shoplist2=['todou','maizi']

>>> shoplist2.extend(shoplist)

>>> shoplist2

['todou', 'maizi', 'apple', 'mango', 'banana', 'rice', 'carrot', 'meat']

4)判斷某個對象是否在list中:obj in listname

>>> 'apple' in shoplist

true

5)在list中搜尋對象:listname.index(obj)

注:如果list中存在多個相同obj,則傳回的是首次出現的索引,如果list中不存在該對象會抛出異常,是以查找對象之前一定要先判斷一下對象是否在list中,以免引起程式崩潰

>>> shoplist.index('apple')

>>> shoplist.index('rice') 

7)删除list中的對象:listname.remove(obj)

注:如果list中存在多個相同obj,則删除的是首次出現的對象,如果list中不存在該對象則會抛出異常,是以在删除之前也要判斷對象是否在list中

>>> shoplist.remove('apple')

['mango', 'banana', 'rice', 'carrot']

對list進行運算

1)相加:listname1 + listname2 

注:結果為新生成一個list,并沒有修改之前的兩個list

>>> shoplist + shoplist2

['mango', 'banana', 'rice', 'carrot', 'meat', 'todou', 'maizi', 'apple', 'mango', 'banana', 'rice', 'carrot', 'meat', 'todou', 'maizi', 'apple', 'mango', 'banana', 'rice', 'carrot', 'meat']

2)倍數:listname*n

>>> shoplist * 2

['mango', 'banana', 'rice', 'carrot', 'mango', 'banana', 'rice', 'carrot']

注意:沒有減法:

>>> shoplist - shoplist2

traceback (most recent call last):

  file "", line 1, in ?