Python列表、元組、字典的異同


Python列表、元組、字典的異同

1,列表:list

可變的數據類型,可以被改變,可以進行嵌套處理,可在一個列表中存儲一個序列的項目

指明一個列表的方法是:使用方括號

代碼示例:

復制代碼
>>> fruit_list = ['apple', 'pear', 'orange', 'banana', 'watermetton', 'strawberry']
>>> lenrth = len(fruit_list)
>>> print lenrth
6
>>> for items in fruit_list:
    print items,

    
apple pear orange banana watermetton strawberry
>>> fruit_list.append('pawpaw')                     ###添加一個元素
>>> fruit_list.del('apple')                        ###列表中刪除一個元素不能用.del(),而是.remove()
SyntaxError: invalid syntax
>>> fruit_list.remove('aple')

Traceback (most recent call last):
  File "<pyshell#10>", line 1, in <module>
    fruit_list.remove('aple')
ValueError: list.remove(x): x not in list
>>> fruit_list.remove('apple')
>>> fruit_list.pop()
'pawpaw'
>>> fruit_list.count('apple')                    ###.count()函數不是統計列表的長度,而是查找列表中某個元素出現的次數,Len(list)用於計算列表長度
0
>>> print fruit_list
['pear', 'orange', 'banana', 'watermetton', 'strawberry']
復制代碼

2,元組

和列表類似,但是元組是不可修改的,可以進行嵌套

指明一個元組的方法:使用圓括號,中間使用“ , ”將項目分隔

創建一個元組:使用逗號分隔,或者使用tuple()函數 eg:1,2,3  ;tuple([1,2,3])

代碼示例:

復制代碼
>>> animal_tuple = ('fish', 'snake', 'wolf',('dog', 'cat', 'sheap'))
>>> len(animal_tuple)                  ##求解元組的長度
4
>>> 1,2,3                              ##創建一個元組
(1, 2, 3)
>>> tuple([1,2,3])
(1, 2, 3)
>>> 
>>> animal_tuple.append('mouse')           ##元組是不可修改的

Traceback (most recent call last):
  File "<pyshell#20>", line 1, in <module>
    animal_tuple.append('mouse')
AttributeError: 'tuple' object has no attribute 'append'
>>> animal_tuple.index('dog')             ##嵌套在元組內的元組元素無法檢索到!!!!!

Traceback (most recent call last):
  File "<pyshell#21>", line 1, in <module>
    animal_tuple.index('dog')
ValueError: tuple.index(x): x not in tuple
>>> animal_tuple.index('fish')               ##元組的開始元素的標號是0
0
復制代碼

3,字典

把鍵和值聯系在一起,其中鍵必須是唯一的,鍵和值之間用冒號:進行分隔

字典的表示方法:使用{},鍵和值之間用冒號“:”隔開,項之間用逗號“,”隔開

代碼示例:

復制代碼
>>> phonebook_dict = {'Alice': '23456', 'Tom':'67890', 'Snowy': '67845'}    ##創建一個字典
>>> phonebook_dict
{'Snowy': '67845', 'Alice': '23456', 'Tom': '67890'}
>>> items = [('Alice', '23456'), ('Tom','67890'), ('Snowy', '67845')]  ##列表轉化為字典
>>> items_dict = dict(items)
>>> items_dict
{'Snowy': '67845', 'Alice': '23456', 'Tom': '67890'}
>>> len(items_dict)
3
>>> change_items = {'Robin': '55667'}
>>> items_dict.update(change_items) ##.update()更新字典內容
>>> items_dict
{'Snowy': '67845', 'Alice': '23456', 'Robin': '55667', 'Tom': '67890'}
>>> items_dict.items()   ##字典轉化為列表.items()函數
[('Snowy', '67845'), ('Alice', '23456'), ('Robin', '55667'), ('Tom', '67890')]
復制代碼

 

4:總結

把序列轉化為列表:.list(seq)             [1,2,3,4]   >>>>.append()  .remove()  .pop() .index()    .count()  len()

把序列轉化為元組:.tuple(seq)          (1,2,3,4)   >>>>>.index()  .count()    len()

把序列轉化為字典: .dict(seq)           {'1' : 'Snowy', '2':'Tom', '3': 'Alice'}    >>>>.update()  .pop()  len()

字典轉化為列表:   items(dict)  

 

PS:string相當於字符元組

       array:只能存儲同種數據類型的數據,區別於list,相比較list使用的空間更小,通過 from array import array 可以使用array模塊

 

zip()是Python的一個內建函數,它接受一系列可迭代的對象作為參數,將對象中對應的元素打包成一個個tuple(元組),然后返回由這些tuples組成的list(列表)

     code:

復制代碼
>>> a = ['1', '2']
>>> b = ['a', 'c', 'd']
>>> zip(a,b)
[('1', 'a'), ('2', 'c')]
>>> zip(*zip(a,b))
[('1', '2'), ('a', 'c')]
>>> a = [[1,2,3],[4,5,6],[7,8,9]]
>>> zip(a)
[([1, 2, 3],), ([4, 5, 6],), ([7, 8, 9],)]
>>> print [row[0] for row in a]
[1, 4, 7]
>>> zip(*a)
[(1, 4, 7), (2, 5, 8), (3, 6, 9)]
復制代碼

(*)操作符與zip函數配合可以實現與zip相反的功能,即將合並的序列拆成多個tuple。


免責聲明!

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



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