元祖
列表:打了激素的数组
元组:带了紧箍咒的列表
元组本身是不可变数据类型,没有增删改 元组内可以存储任意数据类型
创建元祖
#创建一个元组
t = (1,2.3,True,'star')
print(t)
print(type(t))
#元组本身是不可变数据类型,但是当里面包含可变数据类型时,可以间接修改元组的内容
t1 = ([1,2,3],4)
t1[0].append(4)
print(t1)
#元组如果只有一个元素的时候,后面一定要加逗号,否则数据类型不确定
t2 = ('hello') #虽然t2形式是元组,但是因为t2只有一个元素但是没有加上逗号,所以不是元组,t2的数据类型由元素确定了,是一个字符串
t3 = (1,)
print(type(t2))
print(type(t3))
输出结果:
(1, 2.3, True, 'star')
<class 'tuple'>
([1, 2, 3, 4], 4)
<class 'str'>
<class 'tuple'>
元祖特性
索引、切片
allowUsers = ('root','westos','redhat')
print(allowUsers[0])
print(allowUsers[-1])
print(allowUsers[1:])
print(allowUsers[2:])
print(allowUsers[:-1])
print(allowUsers[::-1])
输出结果:
root
redhat
('westos', 'redhat')
('redhat',)
('root', 'westos')
('redhat', 'westos', 'root')
重复
allowUsers = ('root','westos','redhat')
print(allowUsers * 3)
结果:
('root', 'westos', 'redhat', 'root', 'westos', 'redhat', 'root', 'westos', 'redhat')
连接
allowUsers = ('root','westos','redhat')
print(allowUsers + ('linux','python'))
结果:
('root', 'westos', 'redhat', 'linux', 'python')
成员操作符
allowUsers = ('root','westos','redhat')
print('westos' in allowUsers)
print('westos' not in allowUsers)
结果:
True
False
for循环
allowUsers = ('root','westos','redhat')
for i in allowUsers:
print(i)
结果:
root
westos
redhat
zip:两个元组的元素之间一一对应
allowUsers = ('root','westos','redhat')
allowPasswd = ('123','456','789')
for user,passwd in zip(allowUsers,allowPasswd):
print(user,':',passwd)
结果:
root : 123
westos : 456
redhat : 789
元祖的常用方式与应用场景
1、元祖的常用方式
t = (1,2.3,True,'westos','westos')
print(t.count('westos')) ##出现次数
print(t.index(2.3)) ##索引
结果:
2
1
2、元组的应用场景
变量交换数值
a = 1
b = 2
b,a = a,b #先把(a,b)封装成一个元组(1,2) b,a=a,b ---> b,a=(1,2) b = (1,2)[0] a = (1,2)[1]
print(b)
print(a)
结果:
1
2
打印变量的值
name = 'westos'
age = 11
t = (name,age)
print('name:%s , age:%d' %(name,age))
print('name:%s , age:%d' %t)
结果:
name:westos , age:11
name:westos , age:11
元组的赋值
有多少个元素,就用多少个变量接收
t = ('westos',11,100)
name,age,score = t
print(name,age,score)
结果:
westos 11 100
元组排序
score = (100,89,45,78,65)
scoreLi = list(score) ##转换为列表的输出为:[100, 89, 45, 78, 65]
scoreLi.sort() ##排序后:[45, 65, 78, 89, 100]
print(scoreLi)
结果:
[45, 65, 78, 89, 100]
sorted()直接对元组排序 排序后会变成列表
score = (100,89,45,78,65)
scores = sorted(score)
print(scores)
结果:
[45, 65, 78, 89, 100]
去掉一个最大数,去掉一个最小数,求平均成绩
score = (100,89,45,78,65)
scores = sorted(score) ##scores = [45, 65, 78, 89, 100]
minscore,middlescore,maxscore = scores ##赋值的变量可以自定义
print(minscore)
print(middlescore)
print(maxscore)
print('最终成绩为: %.2f' %(sum(middlescore) / len(middlescore))) ##在python中 / 是除号不是取整
结果:
45
[65, 78, 89] ##注意 *middlescore 的用法
100
最终成绩为: 77.33