標籤:
在前面有提高過元組tuple是屬於Sequence中的一種,tuple的元素是使用小括弧()括起來:
tup1 = (1, ‘hello‘, ‘a‘, ‘b‘, ‘c‘, 2.01)print(tup1)#使用for迴圈依次列印tuple中的每一個元素for v in tup1: print(v) #使用下標訪問每一個元素for i in range(len(tup1)): print(tup1[i])>>>1helloabc2.01
tuple的建立非常簡單,只需要把元素用單括弧()括起來即可,元素之間用逗號分隔開。
tuple中可以存放任意類型的元素,即除了上面代碼示範的整數、浮點數、字串,還可以是tuple, list等這些類型。
tup2 = (tup1, ‘tup2‘)#print(tup2)for v in tup2: print(v) >>>(1, ‘hello‘, ‘a‘, ‘b‘, ‘c‘, 2.01)tup2
tuple最大的特點是:建立之後,不能對元素進行修改(包括刪除),修改則會直接報錯。
tup2[1] = ‘abc‘Traceback (most recent call last): File "<pyshell#18>", line 1, in <module> tup2[1] = ‘abc‘TypeError: ‘tuple‘ object does not support item assignment
tuple元素的訪問,上面已經展示了通過下標去訪問,其實還可以進行截取,得到一個子tuple
print(tup1[1:])>>> (‘hello‘, ‘a‘, ‘b‘, ‘c‘, 2.01)print(tup1[1:-1:2])>>> (‘hello‘, ‘b‘)
tuple的串連,可以把兩個tuple進行“+”,將兩個tuple串連為一個新的tuple
tup3=(‘abc‘,) #定義只有一個元素的tuple,需要在後面加上‘,‘print(tup1 + tup3)>>> (1, ‘hello‘, ‘a‘, ‘b‘, ‘c‘, 2.01, ‘abc‘)
擷取tuple元素的個數:
print(len(tup1))
把list轉變為tuple:
list1 = [‘a‘, ‘b‘, ‘c‘]tuple(list1)>>> (‘a‘, ‘b‘, ‘c‘)
Python入門(五) tuple