python数据类型之‘元组’

1.元组的定义

 元组(tuple):    带了紧箍咒的列表;
之所以这样称,是因为元组是不可变数据类型,没有增删改查;     但其可以存储任意数据类型;

1.定义元组

t = (1, 2.1, 2e+10, True, 2j+3, [1,2,3],(1,2,3) )
print(t, type(t))

 如果元组里面包含可变数据类型, 可以间接修改元组内容;

t1 = ([1,2,3], 4)
t1[0].append(4)
print(t1)



元组如果只有一个元素, 后面一定要加逗号, 否则数据类型不确定;

t2 = ()
t3 = tuple([])
t4 = ('hello')
t5 = ('hello',)
print(type(t2), type(t3), type(t4), type(t5))

2.元组的特性

1.重复(*)

allowUsers = ('root', 'westos', 'fentiao')

print(allowUsers*3)

2.连接(+)

allowUsers = ('root', 'westos', 'fentiao')

print(allowUsers + ('fensi', 'fendai'))

3.成员操作符(in)

allowUsers = ('root', 'westos', 'fentiao')

print('westos' in allowUsers)
print('westos' not in allowUsers)

4.索引

5.切片

6.for循环

allowUsers = ('root', 'westos', 'fentiao')
print("显示".center(50, '*'))
for user in allowUsers:
    print("白名单用户:%s" %(user))

# # for循环并且求索引(枚举)

allowUsers = ('root', 'westos', 'fentiao')

print("索引显示".center(50, '*'))
for index,user in  enumerate(allowUsers):###(枚举)
    print("第%d个白名单用户: %s" %(index+1, user))

7.zip: 集和用户名和密码两个元组, 元素之间一一对应

allowUsers = ('root', 'westos', 'fentiao')
allowPasswd = ('123', '456', '789')
for user, passwd in  zip(allowUsers, allowPasswd):
    print(user,':', passwd)

3.元组的常用方法

t = (1,2, 'a', 'c', 'a')
print(t.index('c'))     ####求某个字符的索引值
print(t.count('a'))     ####求某个字符出现的次数

print(len(t))     ###查看元组的长度,即元素个数

4.元组的应用场景

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,b)

2.打印变量值

name = 'westos'
age = 10
t = (name, age)
print("name: %s, age: %d" %(name, age))
print("name: %s, age: %d" %t)

3.元组的赋值:(有多少个元素, 就用多少个变量接收)

t = ('westos', 10, 100)
name, age,score  = t
print(name, age, score)

5.练习

游戏记分器

给出一组用元组表示的成绩,去掉最高分和最低分,求平均成绩

scores = (100, 89, 45, 78, 65)
# 先对元组进行排序
# scoresLi = list(scores)
# scoresLi.sort()
# print(scoresLi)    (可以先将元组转化为列表,再排序)


scores = sorted(scores)
# python3中,*就像一个容器,容纳了中间的所有值
minScore, *middleScore, maxScore = scores
print(minScore, middleScore, maxScore)
print("最终成绩为: %.2f" %(sum(middleScore)/len(middleScore)))

猜你喜欢

转载自blog.csdn.net/forever_wen/article/details/81674562