元組的基本操作:
1.創建一個元組:
tuple=(1,26); tuple1=("15","sy");
創建一個空元組:
tuple=();
元組中只包含一個元素時,需要在元素后面添加逗號來消除歧義;
tuple=(50,)
2.訪問元組:
tup1 = ('physics', 'chemistry', 1997, 2000); tup2 = (1, 2, 3, 4, 5, 6, 7 ); print "tup1[0]: ", tup1[0] print "tup2[1:5]: ", tup2[1:5] #以上實例輸出結果: #tup1[0]: physics #tup2[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')
4.刪除元組:
tup = ('physics', 'chemistry', 1997, 2000); print tup; del tup; print "After deleting tup : " print tup;
5.與字符串一樣,元組之間可以使用 + 號和 * 號進行運算。這就意味着他們可以組合和復制,運算后會生成一個新的元組。
6.
Python元組包含了以下內置函數
1、cmp(tuple1, tuple2):比較兩個元組元素。
2、len(tuple):計算元組元素個數。
3、max(tuple):返回元組中元素最大值。
4、min(tuple):返回元組中元素最小值。
5、tuple(seq):將列表轉換為元組。