元组(tuple)的创建
元组是带了约束的列表,仍可以存放任意数据类型
>>> sheen =(1,'3',True,3.4,[1,4],(1,5))
>>> print(type(sheen))
<class 'tuple'>
默认元组内容是不可改变的,但当元组内包含可变数据类型时,可以间接修改元组
>>> star =([1,4,65],'hello')
>>> star[0].append(10001)
>>> print(star)
([1, 4, 65, 10001], 'hello')
如果元组内只有一个元素,其后要加逗号,否则数据类型不确定
>>> sheen =('star')
>>> print(type(sheen))
<class 'str'>
>>> sheen1 =('star',)
>>> print(type(sheen1))
<class 'tuple'>
元组的常用方法
- count()
- index()
>>> sheen =(1,'morning',[1,9])
>>> print(sheen.count(1))
1
>>> print(sheen.index('morning'))
1
元组的特性
索引
>>> clotho =(1,4,6,8,'sheen')
>>> print(clotho[1])
4
>>> print(clotho[-2])
8
切片
>>> print(clotho[::-1])
('sheen', 8, 6, 4, 1)
>>> print(clotho[:5])
(1, 4, 6, 8, 'sheen')
重复
>>> print(clotho*2)
(1, 4, 6, 8, 'sheen', 1, 4, 6, 8, 'sheen')
连接
>>> print(clotho+('star',)) #只能增加元组
(1, 4, 6, 8, 'sheen', 'star')
成员操作符
>>> print('sheen' in clotho)
True
>>> print('sheen' not in clotho)
False
for 遍历
users=('root','student','sheen')
for item in users:
print(item, end=',')
root,student,sheen,
Process finished with exit code 0
for 循环并且带有索引(枚举)
users=('root','student','sheen')
print("白名单显示".center(50,'*'))
for index,user in enumerate(users):
print("第%d位白名单用户:%s" %(index+1,user))
**********************白名单显示***********************
第1位白名单用户:root
第2位白名单用户:student
第3位白名单用户:sheen
Process finished with exit code 0
zip:一一对应
users=('root','student','sheen')
passwds=('redhat','student','huawei')
print("白名单显示".center(50,'*'))
for user,passwd in zip(users,passwds):
print("白名单用户%s的密码为%s" %(user,passwd))
**********************白名单显示***********************
白名单用户root的密码为redhat
白名单用户student的密码为student
白名单用户sheen的密码为huawei
元组的应用场景
交换变量值
a=11
b=22
b,a=a,b
#先把(a,b)封装成一个元组(11,22)
# b,a = a,b -----> (b,a) =(11,22)
# b=(11,22)[0],a=(11,22)[1]
print(a,b)
打印变量值
name='root'
age = 18
m=(name,age)
print("%s的年龄是%s" %m)
元组的赋值
m=('root',90,100)
name,chinese,math =m
print(name,chinese,math)
root 90 100
Process finished with exit code 0