元組的概念
元組(tuple),是一個有序且不可變的容器,在里面可以存放多個不同類型的元素。和列表(list)的區別在於列表中的數據是可變的。
創建元組:
使用小括號定義元組,元組中的數據可以是不同的數據類型。
# 定義多個數據的元組
tup1 = (10, 20, "aa", True)
print(tup1) # (10, 20, 'aa', True)
print(type(tup1)) # <class 'tuple'>
# 定義單個數據元組,必須有逗號
# 方式1
tup2 = (10,)
print(type(tup2)) # <class 'tuple'>
# 方式2
t1 = 1,
print(t1) # (1,)
print(type(t1)) # <class 'tuple'>
# 如果定義的元組只有一個數據但是沒有逗號,則數據類型為這個唯一的數據的類型。
tup3 = (10)
print(type(tup3)) # <class 'int'>
# 定義空元組
# 方式1
tup4 = ()
print(len(tup4)) # 0
print(type(tup4)) # <class 'tuple'>
# 方式2
tup44 = tuple()
print(len(tup44)) # 0
print(type(tup44)) # <class 'tuple'>
切記: 元組的數據是不可以更改的。
元組的下標
元組(tuple)和列表(list)一樣使用方括號加下標的方式訪問元素。
tup1 = ("tom", "jerry")
print(tup1[0]) # tom
# 超過下標會報異常
print(tup1[2]) # IndexError: tuple index out of range
元組的切片
元組(tuple)和列表(list)一樣存在切片操作。
tup1 = ("tom", "jerry", "tomas", "lisa")
print(tup1[0:1]) # ('tom',)
print(tup1[:-1]) # ('tom', 'jerry', 'tomas')
print(tup1[:-1:2]) # ('tom', 'tomas')
print(tup1[::-1]) # ('lisa', 'tomas', 'jerry', 'tom')
元組常見的方法
len()
獲取元組的長度。
tup1 = ("tom", "jerry", "tom", "lisa")
print(len(tup1)) # 4
index()
返回指定數據首次出現的索引下標。
tup1 = ("tom", "jerry", "tomas", "jerry")
print(tup1.index("jerry")) # 1
count()
統計指定數據在當前元組中出現的次數。
tup1 = ("tom", "jerry", "tom", "lisa")
print(tup1.count("tom")) # 2
元組常見的操作
元組和列表有類似的特殊操作。
+: 兩個元組組合生成新的元組。
tup1 = (10, 20, 30)
tup2 = (40, 50, 60)
print(tup1+tup2) # (10, 20, 30, 40, 50, 60)
*: 重復元組。
tup1 = ("tom", "jerry")
print(tup1*2) # ('tom', 'jerry', 'tom', 'jerry')
in:判斷元素是否存在。
tup1 = ("tom", "jerry")
print("tom" in tup1) # True
print("toms" in tup1) # False
not in: 判斷元素是否不存在。
tup2 = ("tom", "jerry", "jack")
print("tom" not in tup2) # False
print("toms" not in tup2) # True
元組嵌套列表
元組不允許修改、新增、刪除某個元素。但當元組中嵌套列表時,情況就會不一樣。
tup1 = ("a", "b", ["c", "d"])
print(tup1[2][1]) # d
# 當修改元組內部的列表時,可以修改成功。
tup1[2][1] = "xiaoming"
print(tup1) # ('a', 'b', ['c', 'xiaoming'])
所以我們在使用元組時,盡量使用數字、字符串和元組這種不可變的數據類型作為元組的元素,這樣就能確保元組的不可變性。
元組的遍歷
使用for循環
tup1 = ("a", "b", "c", "d")
for i in tup1:
print(i)
使用for循環和range()
tup1 = ("a", "b", "c", "d")
for i in range(len(tup1)):
print(tup1[i])
使用enumerate()函數
tup1 = ("a", "b", "c", "d")
for index, value in enumerate(tup1):
print(value)
使用內置函數iter()
tup1 = ("a", "b", "c", "d")
for value in iter(tup1):
print(value)
