元組 tuple
1. 元組的定義與特點(diǎn)
定義:定義元組使用小括號(hào) ,元素用逗號(hào)隔開。
特點(diǎn):一個(gè)元組可以存儲(chǔ)多個(gè)元素,元素可以是不同的數(shù)據(jù)類型,元素可以重復(fù),元組內(nèi)的數(shù)據(jù)是不可修改的(某個(gè)元素是列表,則可以對(duì)該列表進(jìn)行新增刪除修改操作),也不能進(jìn)行刪除。
# 多個(gè)元素的元組
t1 = (10,20,30)
# 當(dāng)元素的元組
t2 = (10,)
組包方式創(chuàng)建元組:
t3 = 12,13,14
通過(guò) tuple(數(shù)組)函數(shù)創(chuàng)建
list1 = [12,14,15]
t4 = tuple(list1)
注意:定義單個(gè)元素的元組,元素后面最好也添加一個(gè)逗號(hào),否則type(t2) 將輸出int文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-519903.html
t3 = (10,)
print(type(t3)) # tuple
t4 = (30)
print(type(t4)) # int
2. 元組的常見操作
元組不支持 新增 刪除 修改,只支持查找。文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-519903.html
- 根據(jù)下標(biāo)查找
- index(item):查找某個(gè)元素在元組中的索引,不存在則報(bào)錯(cuò)。
- count(item): 統(tǒng)計(jì)元素在元組中出現(xiàn)的次數(shù)。
- len(tuple): 統(tǒng)計(jì)元組中數(shù)據(jù)的個(gè)數(shù)。
tuple1 = ('aa', 'bb', 'cc', 'dd', 'bb', [1, 2, 3])
print(tuple1[2]) # cc
print(tuple1.index('bb')) # 1
print(tuple1.count('bb')) # 2
print(len(tuple1)) # 6
tuple1[5][1] = 9
print(tuple1) # ('aa', 'bb', 'cc', 'dd', 'bb', [1, 9, 3])
3. 元組的應(yīng)用場(chǎng)景
- 自動(dòng)組包
t = 10,23,56 # type(t) 輸出 tuple
- 自動(dòng)拆包
t = 10,23,56
a, b, c = t # a 10, b 23, c 56
- 格式化輸出
t = ('tom', 13)
print('我是 %s , 年齡 %d' %t) # 我是 tom , 年齡 13
- 讓列表不可被修改,數(shù)據(jù)保護(hù)
l = [10,20,30]
# 將列表變成元組 元素就不可變了
t = tuple(l)
到了這里,關(guān)于Python 元組tuple的創(chuàng)建與使用的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!