1. 程式人生 > 其它 >python簡單認識元組

python簡單認識元組

Python 元組
Python的元組與列表類似,不同之處在於元組的元素不能修改。

元組使用小括號,列表使用方括號。

元組建立很簡單,只需要在括號中新增元素,並使用逗號隔開即可。

如下例項:

tup1 = ('physics', 'chemistry', 1997, 2000)
tup2 = (1, 2, 3, 4, 5 )
tup3 = "a", "b", "c", "d"

建立空元組

tup1 = ()

元組中只包含一個元素時,需要在元素後面新增逗號

tup1 = (50,)

元組與字串類似,下標索引從0開始,可以進行擷取,組合等。

訪問元組
元組可以使用下標索引來訪問元組中的值,如下例項:

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)
修改元組
元組中的元素值是不允許修改的,但我們可以對元組進行連線組合,如下例項:

tup1 = (12, 34.56)
tup2 = ('abc', 'xyz')
 

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

建立一個新的元組

tup3 = tup1 + tup2
print tup3
以上例項輸出結果:

(12, 34.56, 'abc', 'xyz')

刪除元組
元組中的元素值是不允許刪除的,但我們可以使用del語句來刪除整個元組,如下例項:

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