標籤:erro list 位置 元素 after type 不同 次數 組合
Python的元組與列表類似,不同之處在於元組的元素不能修改。
元組使用小括弧,列表使用方括弧。
1、元組的定義
tuple1 = ("hello", "world", 100, 200)tuple2 = () # 定義空元祖tuple3 = tuple() # 定義空元祖print type(tuple1), type(tuple2), type(tuple3)#運行結果:<type ‘tuple‘> <type ‘tuple‘> <type ‘tuple‘> 2、訪問元組
tup1 = ("hello", "world", 100, 200);tup2 = (1, 2, 3, 4, 5, 6, 7 );print "tup1[0]: ", tup1[0]print "tup2[1:5]: ", tup2[1:5]#運行結果tup1[0]: hellotup2[1:5]: (2, 3, 4, 5)3、修改/刪除元組
元組中的元素值是不允許修改的,但我們可以對元組進行串連組合,如下執行個體:
tup1 = (12, 34.56);tup2 = (‘abc‘, ‘xyz‘);# 以下修改元組元素操作是非法的。# tup1[0] = 100;# 建立一個新的元組tup3 = tup1 + tup2;print tup3;#運行結果(12, 34.56, ‘abc‘, ‘xyz‘)
元組中的元素值是不允許刪除的,但我們可以使用del語句來刪除整個元組,如下執行個體:
tup = ("hello", "world", 100, 200);#del = tup[2] # 該操作是不合法的del tup;print "After deleting tup : "print tup;#運行結果:After deleting tup : print tup;NameError: name ‘tup‘ is not defined4、元組常用方法
list.index(obj) #從列表中找出某個值第一個匹配項的索引位置
list.count(obj) #統計某個元素在列表中出現的次數
5、元組的內建函數
cmp(tuple1, tuple2) #比較兩個元組元素。
len(tuple) #計算元組元素個數。
max(tuple) #返回元組中元素最大值。
min(tuple) #返回元組中元素最小值。
tuple(seq) #將列錶轉換為元組。
Python 基礎資料類型之tuplu