5.1 元組的介紹

元組:元組也是一個(gè)容器類型,可以存儲(chǔ)多個(gè)數(shù)據(jù),但是元組一旦定義完成,元組里面的數(shù)據(jù)不能修改
元組好比是一個(gè)只讀的列表。
元組的表現(xiàn)形式:(1, 'a')
元組的類型:tuple

元組的使用場(chǎng)景:
  1. 數(shù)據(jù)固定,不會(huì)進(jìn)行修改
  2. 字符串的格式化輸出,比如: print("%d %s" % (1, 'a'))
  3. 函數(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)
  1. 要獲取下標(biāo)的數(shù)據(jù)
  2. 開(kāi)始下標(biāo)
  3. 結(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)單。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容