元組
元組(tuple):元組是不可變的序列,沒有增,刪,改的權(quán)限(即不能修改),只能查詢和使用索引,切片等一些功能。
元組使用小括號,列表使用方括號。
元組最大的好處是可以保證數(shù)據(jù)的安全。
1.創(chuàng)建元組
使用 tuple() 或者 ( ) 直接初始化元組
# 創(chuàng)建一個空元組
t1 = ()
print(t1) # out: ()
# 創(chuàng)建只包含一個值的元組(組中只有一個元素時,后面一定要加逗號,否則數(shù)據(jù)類型不確定)
t2 = (1, )
print(type(t2))
print(t2) # out: (1,)
# 創(chuàng)建一個包含三個元素的元組
t3 = (11, 22, 33)
print(t3) # out: (11, 22, 33)
# 將列表轉(zhuǎn)換成元組
t4 = tuple([1, 2, 3, 4])
print(t4) # out: (1, 2, 3, 4)
# 將字典轉(zhuǎn)換成元組
#針對字典 會返回字典的key組成的tuple
t5 = tuple({'a': 100, 'b': 42, 'c': 9})
print(t5) # out: ('a', 'b', 'c')
# 將字符串轉(zhuǎn)換成元組
t6 = tuple("abc")
print(t6) # out: ('a', 'b', 'c')
# 將區(qū)間轉(zhuǎn)換成元組
t7 = tuple(range(1, 6))
print(t7) # out: (1, 2, 3, 4, 5)
2.元組的訪問和截取
元組可以使用下標索引來訪問元組中的值
語法格式:tuple_name[i]
tup1 = ('physics', 'chemistry', 1997, 2000)
print("tup1[0]: ", tup1[0]) # out: tup1[0]: physics
元組可以可以截取索引中的一段元素
語法格式:tuple_name[start : end : step]
其中step可有可無(默認為1,不能為0),[start, end)范圍為左閉右開
tup2 = (1, 2, 3, 4, 5, 6, 7)
print("tup2[1:6:2]: ", tup2[1:6:2]) # out: tup2[1:6:2]: [2, 4, 6]
print("tup2[1:5]: ", tup2[1:5]) # out: tup2[1:5]: [2, 3, 4, 5]
# 反向讀取,讀取倒數(shù)第二個元素
print('tup2[-2]: ', tup2[-2]) # out: tup2[-2]: 2
# 截取元素,從第二個開始后的所有元素
print('tup2[1:]: ', tup2[1:]) # out: tup2[1:]: (2, 3, 4, 5, 6, 7)
3.修改元組
元組中的元素值是不允許修改的,但可以對元組進行連接組合
'''對元組變量進行重新賦值'''
tup1 = (10, 20)
tup1 = (5, 25.3)
print(tup1) # out: (5, 25.3)
# 以下修改元組元素操作是非法的。
# tup1[0] = 100; #報錯
'''通過連接多個元組(使用`+`或者`*`進行拼接元組)的方式向元組中添加新元素'''
tup2 = (12, 34.56)
tup3 = ('abc')
# 創(chuàng)建一個新的元組
tup4 = tup2 + tup3
tup5 = tup3 * 2
print(tup4) # out: (12, 34.56, 'abc')
print(tup5) # out: ('abc', 'abc')
4.刪除元組
元組中的元素值是不允許刪除的,但可以使用
del()語句來刪除整個元組
tup = ('physics', 'chemistry', 1997, 2000)
print(tup) # out: ('physics', 'chemistry', 1997, 2000)
del(tup)
print(tup) # 刪除tup中的所有元素
5.元組常用方法
tuple.index(obj[,start=0[,end=len(tuple)]]):獲取指定元素的索引號
obj -- 指定檢索的對象。
start -- 可選參數(shù),開始索引,默認為0。(可單獨指定)
end -- 可選參數(shù),結(jié)束索引,默認為元祖的長度。(不能單獨指定)
tup = [1, 2, 3]
tup.index(2) # out: 1
tuple.count(x):獲取元組中元素出現(xiàn)的次數(shù)
tup = [1, 2, 1, 5, 2]
tup.count(2)
# out: 2
sorted(tup):暫時排序
tuple = (11, -10, 22, 999, 33, 44)
# 不改變元組中元素的位置,只是臨時排序,是可以的
print(sorted(tuple)) # out: [-10, 11, 22, 33, 44, 999]
6.元組中的內(nèi)置函數(shù)
len(tuple):計算元組元素個數(shù)
max(tuple):返回元組中元素最大值
min(tuple):返回元組中元素最小值
sum(tuple):計算元組的和
tuple(seq):將列表轉(zhuǎn)換為元組
t1 = (2, 5, 15, 48, 88)
len(t1) # out: 5
max(t1) # out: 81
min(t1) # out: 1
sum(t1) # out: 161
tuple([1,2,4]) # out: (1, 2, 4)