Python有兩個非常相似的集合式的數據類型,分別是list和tuple,定義形式常見的說法是數組。
tuple通過小括號( )定義,定義後無法編輯元素內容(即不可變),而list通過中括號[ ]定義,其元素內容可以編輯(即可變),編輯動作包含刪除pop( )、末尾追加append( )、插入insert( ).
可變的list
>>> name=['cong','rick','long']
>>> name[-2] #等同於name[1]
'rick'
>>> name.append('tony')
>>> name.insert(0,'bob') #在第一個位置即索引0處插入bob
>>> name.insert(2,'Jam')
>>> name
['bob', 'cong', 'Jam', 'rick', 'long', 'tony']
>>> name.pop() #刪除最後的元素
'tony'
>>> name.pop(0) #刪除第一個元素
'bob'
>>> name
['cong', 'Jam', 'rick', 'long']
不可變的tuple
>>> month=('Jan','Feb','Mar')
>>> len(month)
3
>>> month
('Jan', 'Feb', 'Mar')
>>> month[0]
'Jan'
>>> month[-1]
'Mar'
>>> month.appnd('Apr') #編輯元素內容會報錯
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'tuple' object has no attribute 'appnd'
若要編輯通過tuple定義的元素,可先轉換爲list再編輯:
>>> month_1=list(month) #轉換爲list
>>> month_1
['Jan', 'Feb', 'Mar']
>>> month_1.append('Apr') #可追加
>>> month_1
['Jan', 'Feb', 'Mar', 'Apr']
>>> month
('Jan', 'Feb', 'Mar')
>>> month=tuple(month_1) #轉回tuple
>>> month
('Jan', 'Feb', 'Mar', 'Apr')
做個 “可變的”tuple
>>> A= ('a', 'b', ['C', 'D'])
>>> A[2]
['C', 'D']
>>> len(A)
3
>>> A[2][0]
'C'
>>> A[2][0]='GG'
>>> A[2][0]='MM'
>>> A
('a', 'b', ['MM', 'D'])
>>> A[2][0]='GG'
>>> A[2][1]='MM'
>>> A
('a', 'b', ['GG', 'MM'])
>>> print(A[1]) #print()可省略
b
>>> A[2][0]
GG