作者博文地址:http://www.cnblogs.com/spiritman/
Python的元組與列表類似,同樣可通過索引訪問,支持異構,任意嵌套。不同之處在於元組的元素不能修改。元組使用小括號,列表使用方括號。
創建元組
元組創建很簡單,只需要在括號中添加元素,並使用逗號隔開即可
tup1 = () #空元組
tup2 = ('a','b','c','d')
tup3 = (1,2,3,'a','b','c')
元組操作方法及實例展示
可以使用dir(tuple)查看元組支持的操作
count
1 功能:統計元組中某元素的個數 2 語法:T.count(value) -> integer -- return number of occurrences of value 3 T = ('a','b','c','d',1,2,2,3,4) 4 T.count(2) 5 結果:2
index
1 功能:獲取元素在元組中的索引值,對於重復的元素,默認獲取從左起第一個元素的索引值 2 語法:T.index(value, [start, [stop]]) -> integer -- return first index of value.Raises ValueError if the value is not present. 3 T = ('a','b',2,'c','d',1,2,3,4) 4 T.index(2) 5 結果:2 #元素2第一次出現在索引為2的位置 6 T.index(2,3,7) 7 結果:6
T1 + T2
1 功能:合並兩個元組,返回一個新的元組,原元組不變 2 語法:T = T1 + T2 3 T1 = ('a','b','c') 4 T2 = (1,2,3,4) 5 T = T1 + T 2 6 結果:
7 print T 8 ('a','b','c',1,2,3,4) 9 print T1 10 ('a','b','c') 11 print T2 12 (1,2,3,4)
T1 * N
1 功能:重復輸出元組N次,返回一個新元組,原元組不變 2 語法:T = T1 * N 3 T1 = ('a','b',1,2,3) 4 T = T1 * 3 5 結果: 6 print T 7 ('a','b',1,2,3,'a','b',1,2,3,'a','b',1,2,3) 8 print T1 9 ('a','b',1,2,3)
元組雖然不可變,但是當元組中嵌套可變元素時,該可變元素是可以修改的,元組本身不變,使用id(tuple)查看。
1 T = ('a','b','c',[1,2,3,4],1,2,3)
2 id(T)
3 140073510482784 4 print T[3] 5 [1,2,3,4] 6 T[3].append(5) 7 print T[3] 8 [1,2,3,4,5] 9 print T 10 ('a','b','c',[1,2,3,4,5],1,2,3)
11 id(T)
12 140073510482784
元組支持切片操作
1 語法:T[start [, stop[, step]]] 2 實例演示: 3 T = ('a','b','c','d','e','f','g','h') 4 print T[:] #取所有元素 5 ('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h') 6 print T[2:] #取從索引2開始到末尾的元素 7 ('c', 'd', 'e', 'f', 'g', 'h') 8 print T[2:6] #取索引2到6的所有元素,不包含索引6 9 ('c', 'd', 'e', 'f') 10 print T[2:6:2] #從索引2到6,每隔一個元素取一個 11 ('c', 'e')
作者博文地址:http://www.cnblogs.com/spiritman/