python——元组

一、定义元组

# 定义元组
t=(1,2,3,True,'abc')
print(t)                          # 输出元组
print('元组t1的类型为:',type(t))  # 查看类型 

# 元组里包含可变数据类型,可以间接修改元组的内容
t1 = ([1,2,3],4)t1[0].append(4)   # 给元组t1的第一个元素添加元素
print(t1)                         # 输出元组 

# 元组如果只有一个元素的时候,后面一定要加逗号,否则数据类型不确定
t2 = ('hello')t3 = ('hello',)
t4 = (1,)
print('元组t2的类型为:',type(t2))
print('元组t3的类型为:',type(t3))
print('元组t4的类型为:',type(t4))

在这里插入图片描述

二、元组的特性

(1)索引
(2)切片
(3)重复
(4)连接
(5)成员操作符
(6)迭代
(7)枚举
(8)zip(两个元组元素之间一一对应)

列:

allowusers = ('root','westos','redhat')
allowpasswd = ('123','456','789') 

# 索引,切片
print(allowusers[0])
print(allowpasswd[1])
print(allowpasswd[:-1])
print(allowusers[1:])

# 重复
print('\n')
print(allowpasswd*2) 

# 连接
print(allowusers + ('linux','python')) 
print('\n')

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

# for循环
print('\nallowuser 元组中元素分别为:')
for i in allowusers:    
    print(i)
for index,user in enumerate(allowusers):    
    print('第%d个白名单用户: %s' %(index+1,user)
	
# zip:两个元组的元素之间一一对应
print('\n\n一一对应输出元组中元素')
for user,passwd in zip(allowusers,allowpasswd):    
    print(user,':',passwd)

在这里插入图片描述

三、元组常用方法

t= (1,2.3,True,'westos','westos')

# 1.统计元组中元素的个数
print("元组t中'westos'的个数为:",t.count('westos')) 

# 2.查看元组中元素的索引
print('元组t中2.3的索引为:',t.index(2.3))

在这里插入图片描述

四、元组的应用场景

# 1.变量交换数值 
a=1
b=2
b,a=a,b
"""
这一步实际上进行了以下操作:
1.先把(a,b)封装成一个元组(1,2)
2.b,a=a,b ---> b,a=(1,2)
3.b = (1,2)[0]   a=(1,2)[1]
"""
print('a=',a)
print('b=',b) 

# 2.打印变量的值
name = 'westos'
age =18
t= (name,age)
print('\n')
print('name:%s \nage:%d' %t) 

# 3.元组的赋值,又多少个元素,就用多少个变量接收
t = ('westos',16,89)n
ame,age,score=t
print('\n打印被赋值的元组t为:',t)  

# 4.练习
score = (100,65,89,76,53,98)
# 这是第一种排序方法,用sort排序
score1 = list(score)   # 先把score元组转换为列表
score1.sort()          # 用sort对列表进行排序
print('\n排序后的元组为:',score1)          # 输出排序后的列表 

# 这是第二种排序方法,用sorted排序
score2 = sorted(score)
print(score2) 

print('\n')minscore,*middlescore,maxscore = score1
print('最小分数为:',minscore)
print('最大分数为:',maxscore)
print('去除最高分和最低分的分数为:',middlescore)
print('最终成绩为:%.2f' %(sum(middlescore)/len(middlescore))) *middlescore
注:sort与sorted的区别是什么?
score.sort() # 排序方法
score.sorted() # 排序函数

在这里插入图片描述

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值