元組:元組也是一個(gè)容器類型,可以存儲(chǔ)多個(gè)數(shù)據(jù),但是元組一旦定義完成,元組里面的數(shù)據(jù)不能修改
元組好比是一個(gè)只讀的列表。
元組的表現(xiàn)形式:(1, 'a')
元組的類型:tuple
元組的使用場(chǎng)景:
- 數(shù)據(jù)固定,不會(huì)進(jìn)行修改
- 字符串的格式化輸出,比如:
print("%d %s" % (1, 'a'))- 函數(shù)的返回值,也可以使用元組。
示例:
- 定義元組
my_tuple = (1, 3.14, 'abc', range(3), [1, 3, 5], (1, 6)) print(my_tuple, type(my_tuple)) # 結(jié)果是:(1, 3.14, 'abc', range(0, 3), [1, 3, 5], (1, 6)) <class 'tuple'>
- 根據(jù)下標(biāo)獲取元組中的數(shù)據(jù)
result = my_tuple[0] print(result) # 結(jié)果是:1 result = my_tuple[-1] print(result) # 結(jié)果是:(1, 6) value = result[1] print(value) # 結(jié)果是:6 value = my_tuple[-1][1] print(value) # 結(jié)果是:6
- 元組也支持切片獲取數(shù)據(jù)
value = my_tuple[1:3] print(value) # 結(jié)果是:(3.14, 'abc')
- 注意點(diǎn):當(dāng)元組中只有一個(gè)元素(數(shù)據(jù))時(shí),元組中的逗號(hào)不能省略
my_tuple = ('a',) print(my_tuple, type(my_tuple)) # 結(jié)果是:('a',) <class 'tuple'>
5.1.1 元組結(jié)合count和index
示例:
my_tuple = ('a', 'b', 1, 2, 'a')
count:根據(jù)指定數(shù)據(jù)在元組中統(tǒng)計(jì)該數(shù)據(jù)出現(xiàn)的次數(shù)result = my_tuple.count('a') print(result) # 結(jié)果是:2
index:根據(jù)指定數(shù)據(jù)獲取該數(shù)據(jù)在元組的下標(biāo)
- 要獲取下標(biāo)的數(shù)據(jù)
- 開(kāi)始下標(biāo)
- 結(jié)束下標(biāo)(不包含)
index = my_tuple.index('b', 0, 2) print(index) # 結(jié)果是:1
5.1.2 元組的遍歷
遍歷元組和遍歷字符串或者列表非常類似。
示例一:
for 循環(huán)my_tuple = ('譚玹霖', '沐婉卿', '徐光耀') for value in my_tuple: print(value) # 結(jié)果是:譚玹霖 沐婉卿 徐光耀
示例二:
while 循環(huán)# 記錄當(dāng)前的下標(biāo) index = 0 while index < len(my_tuple): # 根據(jù)下標(biāo)獲取數(shù)據(jù) result = my_tuple[index] print(result) # 結(jié)果是:譚玹霖 沐婉卿 徐光耀 index += 1
總結(jié):通過(guò)對(duì)比,只想獲取容器類型中的數(shù)據(jù),使用for循環(huán)比較簡(jiǎn)單。