python 列表、元組 詳解

python中有6種序列的內置類型,分別爲:列表元組字符串Unicode字符串buffer對象xrange對象python

列表和元組是最多見兩種類型。shell

下面將以列表(list)和元組(tuple)爲例對序列操做進行詳細的講解:app

1、列表(list)spa

 列表序列操做有:索引、切片、修改、追加、插入、刪除、擴展、統計、排序(翻轉)、獲取下標、拷貝code

1. 索引 (list[i])對象

 列表的索引序號(又稱爲下標)以下圖所示,該序列一共擁有n個元素,blog

  從左到右索引是從 0 開始,  n-1 爲最後一個元素排序

  從右到左索引是從 -1開始, -n 爲第一個元素索引

animals = ['Dog', 'Cat', 'Monkey', 'Chook', 'Snake']
animals[0]      # 'Dog'
animals[3]      # 'Chook'
animals[-1]     # 'Snake'
animals[-3]     # 'Monkey'
type(animals[1])    # <class 'str'>

 

 注意:經過索引取出的元素類型爲 strrem

 

2. 切片 (list[a:b])

  索引只能取出python列表中的一個元素,此外,python爲取多個列表元素提供了強大的切片操做,經過冒號(:)分割的兩個索引來實現

  注意點:

  1. 切片的索引界限能夠利用諺語 「顧頭不顧尾」 來記憶,也能夠理解爲數學中的左閉右開,數學式爲: [a, b)

  2. 若是省略分隔符前面的索引值,如list[:b],則表示爲從第一個元素開始索引,數學式爲:[0,b)

      若是省略分隔符後面的索引值,如list[a:],則表示爲從a開始索引,索引到最後一個元素結束,此時表現爲 「顧頭又顧尾」,數學式爲[a,end]

  若是兩個索引值所有省略不寫,list[:],此時表示取整個列表

 3. 列表能夠按照某種規則索引元素,如list[first:end:step],frist和end索引與前面的a,b同樣,step表示步長,此方法經常使用於循環中

animals = ['Dog', 'Cat', 'Monkey', 'Chook', 'Snake']
animals[1:3]    # ['Cat', 'Monkey']
animals[3:]     # ['Chook', 'Snake']
animals[:3]     # ['Dog', 'Cat', 'Monkey']
animals[:]      # 整個列表
animals[1:4:2]  # ['Cat', 'Chook']
animals[::2]    # ['Dog', 'Monkey', 'Snake']

 

3. 修改 

animals = ['Dog', 'Cat', 'Monkey', 'Chook', 'Snake']
animals[3] = 'Horse'       #將下標爲3的元素修改成 'Horse'
print(animals)

輸出

['Dog', 'Cat', 'Monkey', 'Horse', 'Snake']

 

4. 追加 (list.append(elem))

 append只能追加一個元素,並且只能追加到列表的最後

animals = ['Dog', 'Cat', 'Monkey', 'Chook', 'Snake']
animals.append('Ox')     # 向列表追加元素
print(animals)

fish = ['freshwater_fish', 'saltwater_fish']     # 魚(淡水魚和鹹水魚)
animals.append(fish)       # 將魚追加到 animals 列表裏
print(animals)

輸出:

['Dog', 'Cat', 'Monkey', 'Chook', 'Snake','Ox']
['Dog', 'Cat', 'Monkey', 'Chook', 'Snake','Ox', ['freshwater_fish', 'saltwater_fish']]

 

5. 插入 (list.inset(i, elem))

 i表明位置,elem表明元素

animals = ['Dog', 'Cat', 'Monkey', 'Chook', 'Snake']
animals.insert(3, 'Horse')
print(animals)

fish = ['freshwater_fish', 'saltwater_fish']
animals.insert(-4, fish)
print(animals)

輸出:

['Dog', 'Cat', 'Monkey', 'Horse', 'Chook', 'Snake']
['Dog', 'Cat', ['freshwater_fish', 'saltwater_fish'], 'Monkey', 'Horse', 'Chook', 'Snake']

 

6. 刪除

   刪除分爲刪除元素和刪除整個列表

   刪除元素的命令有:del,remove,pop

   del list[i]                

   list.remove(elem)            

   list.pop()

>>>animals
['Dog', 'Cat', ['freshwater_fish', 'saltwater_fish'], 'Monkey', 'Horse', 'Chook', 'Snake']
>>>del animals[2]
>>>animals
['Dog', 'Cat', 'Monkey', 'Horse', 'Chook', 'Snake']
>>>
>>>animals.remove('Chook')      # 刪除指定元素
>>>animals
['Dog', 'Cat', 'Monkey', 'Horse', 'Snake']
>>>
>>>animals.pop()        # 刪除最後一個元素
'Snake' 
>>>animals
>>>['Dog', 'Cat', 'Monkey', 'Horse']

刪除整個列表:

del animals     #刪除整個列表

 

7. 擴展  ( list.extend(new_list) )

 擴展是將一個列表追加到另外一個列表,組成一個新的列表

animals = ['Dog', 'Cat', 'Monkey', 'Chook', 'Snake']
fish = ['freshwater_fish', 'saltwater_fish']    
animals.extend(fish)      # 將fish列表追加到animals列表後,組成一個新的列表
print(animals)

輸出:

['Dog', 'Cat', 'Monkey', 'Chook', 'Snake', 'freshwater_fish', 'saltwater_fish']

注意下面的狀況:

animals = ['Dog', 'Cat', 'Monkey', 'Chook', 'Snake']
animals.extend('fish')      
print(animals)

輸出:

['Dog', 'Cat', 'Monkey', 'Chook', 'Snake', 'f', 'i', 's', 'h']

 

8. 統計  list.count(elem)

 統計元素出現的次數

>>>animals = ['Dog', 'Cat', 'Monkey', 'Chook', 'Snake', 'Dog']
>>>animals.count('Dog')
2
>>>animals.count('Cat')
1
>>>animals.count('fish')
0
>>>
>>>cat = 'Cat'
>>>animals.count(cat)
1

 

9. 排序(翻轉)

排序:

  list.sort(self, key=None, reverse=False)

  key 能夠爲int,str, len, lambda等

  reverse能夠爲True和False

數字狀況: 默認從小到大排列

>>> aa = [234, 23, 2, 123]
>>> aa.sort()          # 數字從小到大排列
>>> aa                   # 列表的順序改變了
[2, 23, 123, 234]
>>> aa = [234, 23, 2, 123]
>>> aa.sort(reverse=True)      # 默認從小到大排列,而後轉置了
>>> aa
[234, 123, 23, 2]
>>> aa.sort(key=len)              # 數字不能用len
Traceback (most recent call last):
  File "<pyshell#8>", line 1, in <module>
    aa.sort(key=len)
TypeError: object of type 'int' has no len()

字符串狀況: 默認ASCII表前後順序排列

>>> a = ['x11','abc323','e26','112ddd']
>>> a.sort()       #默認按照ASCII表前後順序排序
>>> a
['112ddd', 'abc323', 'e26', 'x11']
>>> a.sort(key=len)    # 默認第一原則 字符串從短到長排序,第二原則ASCII表前後順序
>>> a
['e26', 'x11', '112ddd', 'abc323']
>>> a.sort(key=len,reverse=True)
>>> a
['112ddd', 'abc323', 'e26', 'x11']

注意: python3.0不容許不一樣數據類型進行排序 

同時有數字和字符串的狀況,不能排序:

>>>a = ['x', 'y', 1, 2]
>>> a.sort()
Traceback (most recent call last):
  File "<pyshell#59>", line 1, in <module>
    a.sort()
TypeError: unorderable types: str() < int()

翻轉:

    list.reverse()

>>> a = ['x', 'y', 1, 2]
>>> a.reverse()
>>> a
[2, 1, 'y', 'x']

 

10. 獲取下標  (list.index(elem))

    list.index(self,value,[start,[stop]])

     value: 帶獲取下標的元素

     start: 開始查詢的下標

      stop:終止查詢的下標

>>> a = ['x', 'y', 1, 'x', 2, 'x']
>>> a.index('x')
0
>>> a.index('x',1)
3
>>> a.index('x',4)
5

 

11. 拷貝 (list.copy())

 list.copy爲淺拷貝,即只爲列表元素的第一層開闢新地址,而第二層共用第一層的地址,也就是說,列表元素的第一層能夠獨立修改,而第二層不可獨立修改,請看下面例子:

>>>list_1 = ['x', 'y', 'z', [1, 2, 3]]  # 建立list_1
>>>list_1_copy = list_1.copy()          # 拷貝list_1
>>>list_1_copy[1] = 'Y'                 # 修改第一層元素的值
>>>print(list_1, list_1_copy)           # 修改的第一層位置元素不一樣
['x', 'y', 'z', [1, 2, 3]] ['x', 'Y', 'z', [1, 2, 3]]
>>>list_1_copy[-1][0] = '123'           # 修改第二層元素的值
>>>print(list_1, list_1_copy)           # 修改的第二層位置元素相同
['x', 'y', 'z', ['123', 2, 3]] ['x', 'Y', 'z', ['123', 2, 3]]

或者用copy模塊的copy方法,一樣是淺拷貝:

import copy
list_1 = ['x', 'y', 'z', [1, 2, 3]]  # 建立list_1
list_2 = copy.copy(list_1)           # 淺拷貝
list_1[1]= 'Y'                       # 改變第一層的值
list_2[-1][-3] = '234'               # 改變第二層的值
print(list_1, list_2)

# 輸出
['x', 'Y', 'z', ['234', 2, 3]] ['x', 'y', 'z', ['234', 2, 3]]

深拷貝須要用deepcopy方法:

import copy
list_1 = ['x', 'y', 'z', [1, 2, 3]]  # 建立list_1
list_3 = copy.deepcopy(list_1)       # 深拷貝
list_1[2]= 'zz'
list_3[-1][-3] = 888
print(list_1, list_3)

#輸出,注意第二層的元素變化狀況
['x', 'y', 'zz', [1, 2, 3]] ['x', 'y', 'z', [888, 2, 3]]

 

2、元組(tuple)

元組與列表相比要簡單不少,由於元組一旦建立成功就不能修改,因此通常稱爲只讀列表

元組的建立與索引:

>>> a = (1, 2, 'a')      # 注意此處的小括號
>>> a
(1, 2, 'a')
>>> a[1]                    # 索引仍然用中括號
2
>>> a[1:]
(2, 'a')

 

tuple只有兩個方法,count和index。

>>> b = ('x', 'y', 1, 'x', 2, 'x')
>>> b.index('x', 1)
3
>>> b.count('x')
3
相關文章
相關標籤/搜索