1. 元組——tuple(元組是一個只讀的list)
(1) 元組的定義
注意:定義單個元素的元組,在元素后面要加上 ','
(2) 元組也支持嵌套
(3) 下標索引取出元素
(4) 元組的相關操作
? ? ? ? 1. index——查看元組中某個元素在元組中的位置從左到右第一次出現的位置
t1 = ("abc", "123", "123", "afg", "doinb")
tmp_pos = t1.index("doinb")
print(f"123 position is {tmp_pos}")
? ? ? ? 2. count——查看元組中某個元素在整個元組中的數量
t1 = ("abc", "123", "123", "afg", "doinb")
tmp_num = t1.count("123")
print(f"123 num is {tmp_num}")
? ? ? ? 3. len——查看元組中所有元素的個數
t1 = ("abc", "123", "123", "afg", "doinb")
tmp_len = len(t1)
print(f"t1 num is {tmp_len}")
? ? ? ? 4. while循環遍歷元組
t1 = ("abc", "123", "123", "afg", "doinb")
tmp_cnt = 0
while tmp_cnt < len(t1):print(f"{t1[tmp_cnt]}")tmp_cnt += 1
? ? ? ? 5. for循環遍歷元組
t1 = ("abc", "123", "123", "afg", "doinb")
for i in t1:print(f"{i}")
(5) 注意:
? ? ? ? 1. 元組中的內容不可修改,但元組中嵌套的列表可以修改
t1 = ("abc", "123", "123", "afg", ["1", "2", "3"])
for i in t1:print(f"{i}")t1[4][1] = "324"
for i in t1:print(f"{i}")
? ? ? ? 2. 元組與列表特性基本相同,但內容不可修改
(6) 總結
(7) 練習
t1 = ('周杰倫', 11, ['football', 'music'])
age_index = t1.index(11)
print(f"age index is {age_index}")
name_index = t1.index('周杰倫')
print(f"name_index is {name_index}")
t1[2].remove('football')
print(t1)
t1[2].append('coding')
print(t1)