Python的元組與列表類似,不同之處在于元組的元素不能修改。
元組使用小括號,列表使用方括號。
元組創(chuàng)建很簡單,只需要在括號中添加元素,并使用逗號隔開即可。
如下實例:
tup1 = ('physics', 'chemistry', 1997, 2000)tup2 = (1, 2, 3, 4, 5 )tup3 = "a", "b", "c", "d"創(chuàng)建空元組
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]以上實例輸出結(jié)果:
tup1[0]: physicstup2[1:5]: (2, 3, 4, 5)
修改元組
元組中的元素值是不允許修改的,但我們可以對元組進行連接組合,如下實例:
#!/usr/bin/python# -*- coding: UTF-8 -*- tup1 = (12, 34.56)tup2 = ('abc', 'xyz') # 以下修改元組元素操作是非法的。# tup1[0] = 100 # 創(chuàng)建一個新的元組tup3 = tup1 + tup2print tup3以上實例輸出結(jié)果:
(12, 34.56, 'abc', 'xyz')
刪除元組
元組中的元素值是不允許刪除的,但我們可以使用del語句來刪除整個元組,如下實例:
#!/usr/bin/python tup = ('physics', 'chemistry', 1997, 2000) print tupdel tupprint "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 tupNameError: name 'tup' is not defined元組運算符
與字符串一樣,元組之間可以使用 + 號和 * 號進行運算。這就意味著他們可以組合和復(fù)制,運算后會生成一個新的元組。
| Python 表達式 | 結(jié)果 | 描述 | 
|---|---|---|
| len((1, 2, 3)) | 3 | 計算元素個數(shù) | 
| (1, 2, 3) + (4, 5, 6) | (1, 2, 3, 4, 5, 6) | 連接 | 
| ('Hi!',) * 4 | ('Hi!', 'Hi!', 'Hi!', 'Hi!') | 復(fù)制 | 
| 3 in (1, 2, 3) | True | 元素是否存在 | 
| for x in (1, 2, 3): print x, | 1 2 3 | 迭代 | 
元組索引,截取
            
新聞熱點
疑難解答