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

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

元組如果只有一個元素的時候,后面一定要加逗號,否則數據類型不確定
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循環
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)變量交換數值
現在給變量賦值,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)
新聞熱點
疑難解答