Python中的元組介紹
1.元組的創(chuàng)建
元組(tuple):元組本身是不可變數(shù)據(jù)類型,沒有增刪改查
元組內可以存儲任意數(shù)據(jù)類型
t = (1,2.3,True,'star') ##例如這里面有數(shù)字,波爾值,和字符 print(t) print(type(t))

元組里面包含可變數(shù)據(jù)類型,可以間接修改元組的內容
t1 = ([1,2,3],4) ##里面含有一個數(shù)組,可以改變里面數(shù)組的值 t1[0].append(4) print(t1)

元組如果只有一個元素的時候,后面一定要加逗號,否則數(shù)據(jù)類型不確定
t2 = ('hello',)
t3 = (1,)
print(type(t2))
print(type(t3))

2.元組的特性
下面是舉例子用的元組
allowUsers = ('root','westos','redhat')
allowPasswd = ('123','456','789')
1)索引和切片
print(allowUsers[0]) print(allowUsers[-1]) print(allowUsers[1:]) print(allowUsers[2:]) print(allowUsers[:-1]) print(allowUsers[::-1])

2)重復
print(allowUsers * 3)
3)連接
print(allowUsers + ('linux','python'))

4)成員操作符
print('westos' in allowUsers)
print('westos' not in allowUsers)

5)for循環(huán)
for user in allowUsers: print(user)

for index,user in enumerate(allowUsers):
print('第%d個白名單用戶: %s' %(index+1,user))

6)zip:兩個元組之間的元素相互對應

3.元組的常用方法
t = (1,2.3,True,'westos','westos')
print(t.count('westos'))
print(t.index(2.3))

4.元組的應用場景
1)變量交換數(shù)值
現(xiàn)在給變量賦值,a=1,b=2。如何使用元組快速的將a和b的值互換
#1.先把(a,b)封裝成一個元組(1,2) #2.b,a=a,b ---> b,a=(1,2) b = (1,2)[0] a = (1,2)[1] print(a) print(b)
這樣就將a,b的值互換了
2)打印變量的值
name = 'westos'
age = 11
t = (name,age)
print('name:%s , age:%d' %(name,age))
print('name:%s , age:%d' %t)

3)元組的賦值,有多少個元素,就用多少個變量
t = ('westos',11,100)
name,age,score = t
print(name,age,score)

4)排序加元組的賦值
score = (100,89,45,78,65)
# scoreLi = list(score)
# scoreLi.sort()
# print(scoreLi)
scores = sorted(score)
# print(scores)
minscore,*middlescore,maxscore = scores
print(minscore)
print(middlescore)
print(maxscore)
print('最終成績?yōu)? %.2f' %(sum(middlescore) / len(middlescore)))

總結
以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作具有一定的參考學習價值,謝謝大家對腳本之家的支持。如果你想了解更多相關內容請查看下面相關鏈接
相關文章
Python位置參數(shù)與關鍵字參數(shù)的區(qū)別
文主要介紹了Python函數(shù)參數(shù)的兩種基本類型:位置參數(shù)和關鍵字參數(shù),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2025-01-01
深度學習Tensorflow2.8?使用?BERT?進行文本分類
這篇文章主要為大家介紹了深度學習Tensorflow2.8?使用?BERT?進行文本分類示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-01-01
python批量處理多DNS多域名的nslookup解析實現(xiàn)
這篇文章主要介紹了python批量處理多DNS多域名的nslookup解析實現(xiàn),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2020-06-06

