一、元组的创建
1. 元组(tuple):不可变数据类型 ,元组内可以存储任意数据类型
t = (1,2.3,True,'westos') #整型、浮点型、布尔型、字符型
print(t)
print(type(t))
2. 元组中可以嵌套列表
t1 = ([1,2,3],4)
print(t1)
t1[0].append(4)
print(t1)
t2 = ('westos') #字符串类型
print(type(t2))
t2 = ('westos',) #元组类型
print(type(t2))
二、元组的特性
1. 索引 切片
users = ('root','westos','redhat')
print(users[0])
print(users[-1])
print(users[1:])
print(users[::-1])
2.重复
users = ('root','westos','redhat')
print(users)
print(users * 3)
3. 连接
users = ('root','westos','redhat')
passwds = ('123','456','789')
print(users + passwds)
print(passwds + ('000','111'))
4. 成员操作符
users = ('root','westos','redhat')
print('redhat' in users)
print('redhat' not in users)
5. 迭代
users = ('root','westos','redhat')
for user in users:
print(user)
6. 枚举
users = ('root','westos','redhat')
for index,user in enumerate(users):
print('第%d个用户:%s' %(index+1,user))
7. zip压缩
users = ('root','westos','redhat')
passwds = ('123','456','789')
for user,passwd in zip(users,passwds):
print(user,':',passwd)
三、元组的常用方法
1. 计数
t =(1,2.3,True,'westos','westos')
print(t.count('westos'))
2. 通过元组项求索引值
t =(1,2.3,True,'westos','westos')
print(t.index(1))
print(t.index(2.3))
四、元组的应用场景
1. sort
scores = (59,89,65,78,100)
scoresli = list(scores) #将元组转化为列表
scoresli.sort() #对列表进行排序
print(scoresli)
scores = (59,89,65,78,100)
scores.sort() #元组不能直接进行排序
print(scores)
2. sorted
scores = (59,89,65,78,100)
scores = sorted(scores)
print(scores)
3. 元组中的应用
scores = (59,89,65,78,100)
minscore,*middlescore,maxscore = scores #其中,*表示多个元素
print(minscore)
print(middlescore)
print(maxscore)
print('最终成绩为:%.2f' %(sum(middlescore)/len(middlescore)))