Python-元组

元组(tuple):元组本身是不可变数据类型,没有增删改查
元组内可以存储任意数据类型


>>> t = (1,2.3,True,'hello')
>>> type(t)
<class 'tuple'>    #tuple表示元组

#元组里面包含可变数据类型,可以间接修改元组的内容
t1 = ([1,2,3],4)
t1[0].append(4)
print(t1)

#元组如果只有一个元素的时候,后面一定要加逗号,否则数据类型不确定
t2 = ('hello',)
t3 = (1,)
print(type(t2))
print(type(t3))
元组的特性:
allowUsers = ('root','westos','redhat')
allowPasswd = ('123','456','789')

#索引 切片
print(allowUsers[0])
print(allowUsers[-1])
print(allowUsers[1:])
print(allowUsers[2:])
print(allowUsers[:-1])
print(allowUsers[::-1])

#重复
print(allowUsers * 3)

#连接
print(allowUsers + ('linux','python'))

#成员操作符
print('westos' in allowUsers)
print('westos' not in allowUsers)

#for循环
for user in allowUsers:
    print(user)
#枚举
for index,user in enumerate(allowUsers):
    print('第%d个白名单用户: %s' %(index+1,user))
#压缩
#zip:两个元组的元素之间一一对应
for user,passwd in zip(allowUsers,allowPasswd):
    print(user,':',passwd)
元组的常用方法:
t = (1,2.3,True,'westos','westos')
print(t.count('westos'))
print(t.index(2.3))
#变量交换数值
 a = 1
 b = 2
 b,a = a,b
 #1.先把(a,b)封装成一个元组(1,2)
 #2.b,a=a,b ---> b,a=(1,2)
 b = (1,2)[0]
 a = (1,2)[1]
 print(a)
 print(b)
#打印变量的值
 name = 'westos'
 age = 11
 t = (name,age)
 print('name:%s , age:%d' %(name,age))    #调用变量的方式打印
 print('name:%s , age:%d' %t)             #调用元组的方式打印
#元组的赋值,有多少个元素,就用多少个变量接收
 t = ('westos',11,100)
 name,age,score = t
 print(name,age,score)
#元组不支持使用.sort()排序,即便数据类型相同,也不能排序,如果数据类型相同,可以先强制转换为列表,然后再进行排序;或者使用sorted函数排序
>>> score = (1,23,21,5,6,3)
>>> score.sort
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'tuple' object has no attribute 'sort'
>>> sortlist=list(score)
>>> sortlist
[1, 23, 21, 5, 6, 3]
>>> sortlist.sort()
>>> sortlist
[1, 3, 5, 6, 21, 23]

>>> score
(1, 23, 21, 5, 6, 3)
>>> scores=sorted(score)
>>> scores
[1, 3, 5, 6, 21, 23]
>>> minscore,*middlescore,maxscore = scores     #将最小值,最大值,和中间值分别赋给三个变量,其中,中间值以列表的类型赋给变量
>>> print(minscore,"---",middlescore,"---",maxscore)
1 --- [3, 5, 6, 21] --- 23


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值