- 元组的创建
元组(tuple):元组本身是不可变数据类型,没有增删改查
元组内可以存储任意数据类型
t = (1,2.3,True,'star')
print(t)
print(type(t))
运行结果为:
(1, 2.3, True, 'star')
<class 'tuple'>
- 元组里面包含可变数据类型,可以间接修改元组内容
t1 = ([1,2,3],4)
t1[0].append(4)
print(t1)
运行结果为:
([1,2,3,4],4)
- 元组里如果只有一个元素的时候,后面要加逗号,否则数据类型不确定
t2 = ('hello',)
print(type(t2))
运行结果为:
<class 'str'>
-
元组里面包含可变数据类型,可以间接修改元组内容
-
元组的特性
allowusers = (‘root’,‘westos’,‘redhat’)
allowpasswd = (‘123’,‘456’,‘789’)
- 索引 切片
print(allowusers[0])
print(allowusers[-1])
print(allowusers[1:])
print(allowusers[:-1])
print(allowusers[::-1])
运行结果为:
('root','westos','redhat')
('redhat')
('westos','redhat')
('root','westos')
('redhat','westos','root')
- 重复
print(allowusers * 3)
运行结果为:
('root','westos','redhat','root','westos','redhat','root','westos','redhat')
- 连接
print(allowusers + ('linux','python'))
运行结果为:
('root','westos','redhat','linux','python')
- 成员操作符
print('westos' in allowusers)
print('westos' not in allowusers)
运行结果为:
True
False
- for循环
for user in allowusers:
print(user)
运行结果为:
root
westos
redhat
for index,user in enumerate(allowusers):
print('第%d个白名单用户: %s' %(index+1,user))
运行结果为:
第1个白名单用户:root
第2个白名单用户:westos
第3个白名单用户:redhat
for user,passwd in zip(allowusers,allowpasswd):
print(user,':',passwd)
运行结果为:
root : 123
westos : 456
redhat : 789
- 元组中常用的方法
t = (1,2.3,True,'linux')
print(t.count('linux'))
print(t.index(1))
运行结果为:
1
0
-
元组的应用场景
-
元组的赋值,有多少个元素,就用多少个变量接收
t = ('westos',11,100)
name,age,score = t
print(name,age,score)
运行结果为:
westos 11 100
scores = (100,89,45,78,65)
scoresLi = list(scores)
scoresLi.sort()
print(scoresLi)
运行结果为:
[ 45,65,78,89,100]
scores = sorted(scores)
print(scores)
运行结果为:
[ 45,65,78,89,100]
scores=(45,65,78,89,100)
minscore,*middlescore,maxscore = scores
print(minscore)
print(middlescore)
print(maxscore)
运行结果为:
45
[65,78,89]
100