1. 程式人生 > >數據結構-元組

數據結構-元組

輸出結果 元素 max image err png http trace 允許

定義:

1) () 來定義,列表是[]

2) 有序, 同列表

3) 創建後本元組不能更改, 列表可以更改

可以通過元組與元組想加得到新的元組

舉例: a = (1, 2, apple)

註意: 元祖一旦創建,不能修改

一、創建元組
tup1 = (‘physics‘, ‘chemistry‘, 1997, 2000);
tup2 = (1, 2, 3, 4, 5 );
tup3 = "a", "b", "c", "d";
創建空元組
tup1 = ();
元組中只包含一個元素時,需要在元素後面添加逗號來消除歧義
tup1 = (50,);
元組與字符串類似,下標索引從0開始,可以進行截取,組合等。

二、訪問元組


同列表一樣

元組可以使用下標索引來訪問元組中的值,如下實例:
#!/usr/bin/python

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]


三、修改元組
元組中的元素值是不允許修改的,但我們可以對元組進行連接組合,如下實例:
#!/usr/bin/python

tup1 = (12, 34.56);
tup2 = (‘abc‘, ‘xyz‘);

# 以下修改元組元素操作是非法的。
# tup1[0] = 100;

# 創建一個新的元組
tup3 = tup1 + tup2;
print tup3;
#以上實例輸出結果:
#(12, 34.56, ‘abc‘, ‘xyz‘)


四、刪除元組
元組中的元素值是不允許刪除的,但我們可以使用del語句來刪除整個元組,如下實例:
#!/usr/bin/python

tup = (‘physics‘, ‘chemistry‘, 1997, 2000);

print tup;
del tup;
print "After deleting tup : "
print tup;
#以上實例元組被刪除後,輸出變量會有異常信息,輸出如下所示:
#(‘physics‘, ‘chemistry‘, 1997, 2000)
#After deleting tup :
#Traceback (most recent call last):
# File "test.py", line 9, in <module>
# print tup;
#NameError: name ‘tup‘ is not defined[/code]



五、元組運算符
與字符串一樣,元組之間可以使用 + 號運算。這就意味著他們可以組合和復制,運算後會生成一個新的元組。

技術分享

why?

、元組的方法

技術分享

1: count

2: index

、元組內置函數
Python元組包含了以下內置函數
1、cmp(tuple1, tuple2):比較兩個元組元素。
2、len(tuple):計算元組元素個數。
3、max(tuple):返回元組中元素最大值。
4、min(tuple):返回元組中元素最小值。
5、tuple(seq):將列表轉換為元組。

數據結構-元組