python 列表、元組 詳解


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

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

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

一、列表(list)

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

1. 索引 (list[i])

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

  從左到右索引是從 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'>

 

 注意:通過索引取出的元素類型為 str

 

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]]

 

二、元組(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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM