python学习笔记—16—数据容器之元组
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)