列表和元組是Python中最常用的兩種數(shù)據(jù)結(jié)構(gòu)汤踏,字典是第三種氢哮。 相同點:
- 都是序列
- 都可以存儲任何數(shù)據(jù)類型
- 可以通過索引訪問
圖片.png
語法差異
使用方括號[]創(chuàng)建列表,而使用括號()創(chuàng)建元組千扔。 請看以下示例:
>>> l = ["https://china-testing.github.io/", "https://www.oscobo.com/"]
>>> t = ("https://china-testing.github.io/", "https://www.oscobo.com/")
>>> print(l)
['https://china-testing.github.io/', 'https://www.oscobo.com/']
>>> print(t)
('https://china-testing.github.io/', 'https://www.oscobo.com/')
>>> print(type(l))
<class 'list'>
>>> print(type(t))
<class 'tuple'>
是否可變
列表是可變的憎妙,而元組是不可變的,這標(biāo)志著兩者之間的關(guān)鍵差異曲楚。
我們可以修改列表的值厘唾,但是不修改元組的值。
由于列表是可變的龙誊,我們不能將列表用作字典中的key抚垃。 但可以使用元組作為字典key。
>>> l[1] = "http://www.reibang.com/u/69f40328d4f0"
>>> l
['https://china-testing.github.io/', 'http://www.reibang.com/u/69f40328d4f0']
>>> t[1] = "http://www.reibang.com/u/69f40328d4f0"
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment
重用與拷貝
元組無法復(fù)制趟大。 原因是元組是不可變的鹤树。 如果運行tuple(tuple_name)將返回自己。
>>> copy_t = tuple(t)
>>> print(t is copy_t)
True
>>> copy_l = list(l)
>>> print(l is copy_l)
False
參考資料
- 討論 項目實戰(zhàn)討論QQ群630011153 144081101
- 本文最新版本地址
- 本文涉及的python測試開發(fā)庫 謝謝點贊逊朽!
- 本文相關(guān)海量書籍下載
- python工具書籍下載-持續(xù)更新
大小差異
Python將低開銷的較大的塊分配給元組罕伯,因為它們是不可變的。 對于列表則分配小內(nèi)存塊叽讳。 與列表相比追他,元組的內(nèi)存更小。 當(dāng)你擁有大量元素時绽榛,元組比列表快湿酸。列表的長度是可變的婿屹。
>>> l = ["https://china-testing.github.io/", "https://www.oscobo.com/"]
>>> t = ("https://china-testing.github.io/", "https://www.oscobo.com/")
>>> print(l.__sizeof__())
56
>>> print(t.__sizeof__())
40
同構(gòu)與異構(gòu)
習(xí)慣上元組多用于用于存儲異構(gòu)元素灭美,異構(gòu)元素即不同數(shù)據(jù)類型的元素,比如(ip,port)昂利。 另一方面届腐,列表用于存儲異構(gòu)元素,這些元素屬于相同類型的元素蜂奸,比如[int1,in2,in3]犁苏。