Python有哪些数据容器?

---list(列表)、tuple(元组)、str(字符串)、set(集合)、dict(字典)

Tuple (元组)

同列表一样,可以封装多个、不同类型的元素在内,元组一旦定义完成,就不可修改(增加删除等)(可看成只读的list)

---定义格式

# 定义元组变量
变量名称 = (元素,元素,...,元素)
# 定义空元组
变量名称 = ()       # 方式1
变量名称 = tuple()  # 方式2

元组只有一个数据,这个数据后面要添加逗号

t1 = ('hhh',)

可嵌套元组

下表索引取出内容 eg: t1[1] , t2[0] [3]

元组共三个方法:index()、count()、函数 len( t1 )

- 根据 index() ,查找特定元素的第一个匹配项,存在则返回对应的下标

t1 = (1,2,'hello',3,4,'hello')
print(t1.index('hello'))   # 结果:2

- 统计某个元素在元组中出现的次数

t1 = (1,2,'hello',3,4,'hello')
print(t1.count('hello'))   # 结果:2

- 统计元组内元素的个数

t1 = (1,2,'hello',3,4,'hello')
print(len(t1))   # 结果:6

-元组的遍历

---while  --- for

t1 = (1,2,'hello',3,4,'hello')
print("while:\t",end=' ')
index = 0
while index < len(t1):
    print(t1[index],end=' ')
    index += 1

print("\nfor:\t",end=' ')
for i in t1:
    print(i,end=' ')

注意:元组本身的内容是不可以修改的,但是如果元组里面的元素是可修改的,可以对该元素内部元素进行修改,例如list等

- 元组综合应用

t1 = ('周杰轮',11,['football','music'])
print(f"年龄所在下标:{t1.index(11)}")
print(f"学生姓名:{t1[0]}")
t1[2].pop(0)
t1[2].append('coding')
print(t1)
"""
年龄所在下标:1
学生姓名:周杰轮
('周杰轮', 11, ['music', 'coding'])
"""

更多推荐