Day27(0211) <<
Previous Next >> Day28(0212)
tuple序對
tuple序對是由一連串資料所組成、不可改變內容(immutable)且有順序的序列(sequence)。序對中的資料以逗號隔開,前後已中括號標示,例如:
>>>(1,"Taiwan",2,"Japan")
(1,'Taiwan',2,'Japan')
建立序對
利用Python內建的tuple()函式來建立序對,例如:
>>>tuple1 = tuple()
>>>tuple1
()
>>>tuple2 = tuple((1,2,3))
>>>tuple2
(1,2,3)
序對的運算
序對支援所有共同的序列運算,len()、max()、min()和sum()等內建函式均適用於序對,例如:
>>>L = (1,2,3,4,5)
>>>len(L)
5 #序對參數L長度為5
另外也可利用連接運算子(+)、重複運算子(*)、比較運算子(>、<、>=、<=、==、!=)、in & not in運算子、索引運算子([])、片段運算子([start:end]),例如:
>>>(1,2,3)+("Taiwan","Japan","Korea")
(1,2,3,'Taiwan','Japan','Korea')
>>>
>>>5*(1,2,3)
(1,2,3,1,2,3,1,2,3,1,2,3,1,2,3)
>>>
>>>(1,2,3) == (3,2,1)
False
>>>
>>>(1,2,3) != (1,2,3,4)
Ture
>>>
>>>(1,2,3) < (1,2,3,4)
Ture
>>>
>>>"Taiwan" in (1,"Taiwan",2)
True
>>>
>>>"Thailand" not in (1,Taiwan,2)
True
>>>
>>>L = (1,2,3,4,5)
>>>L[0]
1
>>>L[1:3]
(2,3)
序對亦支援如下方法:
1.tuple.index(x):傳回參數x所指定的元素第一次出現在序對中的索引,例如:
>>>T = (1,2,3,4,5,6,7,8,9,10)
>>>T.index(3)
2
2.tuple.count(x):傳回參數x所指定的元素第一次出現在序對中的次數,例如:
>>>T = (1,2,3,2,5,6,2,8,9,2)
>>>T.count(2)
4
Day27(0211) <<
Previous Next >> Day28(0212)