一、元组的创建
元组(tuple):
元组本身是不可变数据类型,没有增删改查
元组内可以存储任意数据类型
t = (1,2.3,True,‘star’)
print(t)
print(type(t))
虽然元组没有增删改查,但是我们可以通过修改元组中的可变数据类型来间接修改元组内容。
# t1 = ([1,2,3],4)
# t1[0].append(4)
# print(t1)
#元组里如果只有一个元素的时候,后面要加逗号,否则数据类型不确定
t2 = ('hello',)
print(type(t2))
二、元组的特性
Allowuses = ('root','redhat','ftp')
Allowpasswd = ('123','456','789')
#索引
print(Allowuses[0])
print(Allowpasswd[-1]
#切片
print(Allowuses[1:])
print(Allowuses[:-1])
print(Allowuses[::-1])
#重复
print(Allowuses * 3)
#连接
print(Allowuses + ('linux','python'))
#成员操作符
print(‘westos’ in Allowuses)
print(‘westos’ not in Allowuses)
#for循环
for user in Allowuses:
print(user)
for index,user in enumerate(allowusers):
print('第%d个白名单用户: %s' %(index+1,user))
for user,passwd in zip(allowusers,allowpasswd):
print(user,':',passwd)
三、元组的常用方法
t = (1,2.3,True,'linux')
print(t.count('linux')) #统计linux字符串出现的次数
print(t.index(1)) #打印出1这个元素在元组中的索引值
四、元组的应用场景
#元组的赋值,有多少个元素,就用多少个变量接收
t = ('westos',11,100)
name,age,score = t
print(name)
print(age)
print(score)
print(name,age,score)
类型之间的转换:
t = (100,78,89,32,23)
lt = list(t) #将元组转化为列表
print(lt)
lt.sort()
print(lt)
t = (100,78,89,32,23)
lt = list(t) print(lt)
lt = sorted(lt)
print(lt)
minscore,*middlescore,maxscore = lt
print(minscore)
print(middlescore)
print(maxscore)