python 元組tuple與列表list的區別

元組:不可變列表 & 記錄

使用help可查看到tuple list的內置屬性區別:
T = (1, 2, ‘s1’)
L = [1, 2, ‘s1’]

不可變列表 這一說法,從屬性中可以看出,list中與增減改元素的屬性,tuple都沒有。

元組的內置屬性

T.count(value) -> integer
return number of occurrences of value

T.index(value, [start, [stop]]) -> integer
return first index of value.

列表的內置屬性

 L.append(object) -> None 
 -- append object to end
L.extend(iterable) -> None 
-- extend list by appending elements from the iterable
L.clear() -> None 
-- remove all items from L
L.insert(index, object) 
-- insert object before index
L.pop([index]) -> item 
-- remove and return item at index (default last).
L.remove(value) -> None 
-- remove first occurrence of value.
L.reverse() 
-- reverse *IN PLACE*
L.sort(key=None, reverse=False) -> None 
-- stable sort *IN PLACE*
L.copy() -> list 
-- a shallow copy of L
L.count(value) -> integer 
-- return number of occurrences of value
L.index(value, [start, [stop]]) -> integer 
-- return first index of value.

元組與記錄

元組的記錄功能,即沒有字段,只靠位置索引來記錄數據。
因爲沒有字段,所以正是位置信息給數據賦予了意義,位置不同代表記錄的內容不同。

city, year, area = ('Shanghai', 2020, 123.5)
元組拆包 unpacking

將任意可迭代對象,賦值給左側一個元組。(要求可迭代對象元素個數與左側元組空擋數一致。)
左側元組,可使用 * 來忽略多餘的元素;使用佔位符 _ 來忽略不感興趣的數據。

a, b = b, a    # 不使用中間變量交換兩個變量的值

使用 * 將可迭代對象拆包,作爲函數的參數

def func(a, b, c):
	pass
	
t = [1, 2, 3]
func( *t )

使用 * 來處理剩餘的元素

a, *rest, b, c = range(5)
# a=0, rest=[1, 2], b=3, c=4
# *rest 可出現在任意位置
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章