標籤:改變 rac erro sort 逗號 建立 對象 list 表示
元組由簡單的對象組構成,元組與列表相似,但是元組不能在原處修改。元組位置有序的對象集合,元組通過位移來訪問。
為什麼有了列表還要元組?元組的不變性提供了某種完整性,可以確保元組在程式中不被另一個引用修改,元組類似於其他語言中的常數。
元組用圓括弧表示,對象用逗號分隔。
>>> T = (1,2,3,4,5) #建立元組>>> T[0],T[2:3] #索引;分區 下標從0開始,有起始位置的包前不包後(1, (3,))>>> T[0],T[2:5](1, (3, 4, 5))
>>> T =(‘c‘,‘a‘,‘b‘,‘d‘)>>> sorted(T) #兩種排序方法,sort()和sorted()[‘a‘, ‘b‘, ‘c‘, ‘d‘] #排序以後變成列表>>> T(‘c‘, ‘a‘, ‘b‘, ‘d‘)>>> T.sort() #不能直接對元組使用sort,因為元組不可變Traceback (most recent call last): File "<pyshell#7>", line 1, in <module> T.sort()AttributeError: ‘tuple‘ object has no attribute ‘sort‘>>> tmp = list()>>> tmp = sorted(T)>>> tmp[‘a‘, ‘b‘, ‘c‘, ‘d‘]>>> T = (1,2,3,4,5,6,2,3,2,5,6,1) #索引與計數>>> T.index(2) #第一個2出現的位置1>>> T.index(2,2) #第二個2出現的位置6>>> T.count(2) #總共2出現的次數3
元組不可改變,但是元組內部嵌套的列表可以改變。
>>> T=(1,[2,3],4)>>> T[1]=‘ok‘Traceback (most recent call last): File "<pyshell#17>", line 1, in <module> T[1]=‘ok‘TypeError: ‘tuple‘ object does not support item assignment>>> T[1][0]=‘ok‘>>> T(1, [‘ok‘, 3], 4)
python學習筆記(一)元組tuple