Python學習之路----元組簡介

元組

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

所謂元組的不可變指的是元組所指向的內存中的內容不可變

元組的創建

元組創建只需要在括號中添加元素,並使用逗號隔開即可。

tup1 = ('Google', 'Runoob', 1997, 2000)
tup2 = (1, 2, 3, 4, 5 )
tup3 = "a", "b", "c", "d"   #  不需要括號也可以

print(type(tup3))

>>><class 'tuple'>

創建空元組:

tup_empty = ()

創建一個只包含一個元素的元組:

tup_one = (2,)
tup_int = (2)

print(type(tup_one))
print(type(tup_int))

'''
<class 'tuple'>
<class 'int'>
'''

訪問元組

tup1 = ('Google', 'Runoob', 1997, 2000)
tup2 = (1, 2, 3, 4, 5, 6, 7 )
 
print ("tup1[0]: ", tup1[0])
print ("tup2[1:5]: ", tup2[1:5])

'''
tup1[0]:  Google
tup2[1:5]:  (2, 3, 4, 5)
'''

修改元組

雖然不能修改元組中的元素,但是可以對元組進行連接組合

tup1 = (12,23,45,6.6)
tup2 = ('abc','def')

tup1 = tup1 + tup2
print(tup1)

'''
(12,23,45,6.6,'abc','def')
'''

刪除元組

雖說不能修改元組中的元素(包括刪除),但是可以刪除整個元組

tup = ('Google', 'Runoob', 1997, 2000)
 
print (tup)
del tup
print ("刪除後的元組 tup : ")
print (tup)
'''
('Google', 'Runoob', 1997, 2000)
刪除後的元組 tup : 
Traceback (most recent call last):
  File "F:\Python\Program\test.py", line 6, in <module>
    print (tup)
NameError: name 'tup' is not defined
'''

元組內置函數

len(tuple) 計算元組元素個數。

max(tuple) 返回元組中元素最大值。

min(tuple) 返回元組中元素最小值

tuple(iterable) 將可迭代系列轉換爲元組。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章