Python数据类型认识
- 元组 tuple
- 创建
- 访问
- for循环遍历元组
- 检查项目是否存在
- 更改
- 删除
- 元组连接/复制
- 常用方法
- count()
- index()
- len()
- tuple()
- del
- max()、min()
- 案例 - 座位随机(1)
- 案例 - 座位随机(2)
- 案例 - 统计分数范围
- 总结
元组 tuple
元组是有序且不可更改的集合。在Python中,元组使用圆括号 ()
编写的
创建
元组的创建很简单,使用圆括号 () 直接创建或者使用 tuple() 函数创建,只需要在圆括号中添加元素,并使用逗号隔开即可
''' 1. 使用 () 创建元组 '''
# 元组是一种不可变的数据容器,是有序的
t1 = (12, 4, 6) # 创建一个元组 <class 'tuple'> 元组类型
print(type(t1))
# 元组 不可变 -> 增删改<不能做> 查<能做>
# 列表中所有查找都能在元组中使用
print(t1[2]) # 6
''' 元组(单个元素)'''
# 重点:当元组中只包含一个元素时,需要在元素后面添加逗号, ,否则括号会被当作运算符使用
tuple_1 = (20)
print(type(tuple_1)) # <class 'int'>
tuple_2 = (20,)
print(type(tuple_2)) # <class 'tuple'>
''' 2. 使用 tuple()函数 创建元组 '''
# 通过关键字创建元组
t3 = tuple()
print(type(t3))
# 示例
cre_tuple = tuple(('a', 'b', 'c')) # 注意双括号
print(cre_tuple) # ('a', 'b', 'c')
print(type(cre_tuple)) # <class 'tuple'>
'''
元组 VS 列表
在Python中,元组与列表相似,不同之处在于元组的元素不能修改,而列表的元素可以修改。
元组使用 小括号(),列表使用 中括号[]
'''
访问
和列表一样,我们既可以使用下标索引访问元组中的某个元素(得到一个元素的值),也可以使用切片访问元组中的一组元素(得到是子元组)。
'''
和列表一样,既可以使用下标索引访问元组中的某个元素(得到一个元素的值),也可以使用切片访问元组中的一组元素(得到是子元组)
'''
# 下标索引访问
tuple_name = ('wzq', 'lgl', 'gz', 'whl', 'sj', 'hxw')
print(tuple_name[0]) # wzq
print(tuple_name[-1]) # hxw
# 切片访问
tuple_name = ('wzq', 'lgl', 'gz', 'whl', 'sj', 'hxw')
print(tuple_name[1:5:2]) # ('lgl', 'whl')
print(tuple_name[-6:-1:3]) # ('wzq', 'whl')
for循环遍历元组
fruit_tuple = ('apple', 'pear', 'cherry')
for i in fruit_tuple:
print(i)
apple
pear
cherry
检查项目是否存在
# 检查元组中是否存在'apple'
fruit_tuple = ('apple', 'pear', 'cherry')
print('apple' in fruit_tuple) # True
更改
创建元组后,我们将无法更改其值。元组是不可变的,或者也被称为恒定的。
但是有一种解决方法:可以先将元组转换为列表,更改列表值,然后再将其转换回元组。
''' 元组不可变性 '''
# 所谓元组的不可变性指的是元组所指向的内存中的内容不可变
tup = ('A', 'B', 'C')
# tup[0] = 'a' # 不支持修改元素,会报错 TypeError: 'tuple' object does not support item assignment
''' 可通过转换修改数据 '''
# 创建元组后,我们将无法更改其值。元组是不可变的,或者也被称为恒定的
# 但是有一种解决方法:可以先将元组转换为列表,更改列表值,然后再将其转换回元组
fruit_tuple = ('apple', 'pear', 'cherry')
fruit_list = list(fruit_tuple)
fruit_list[2] = 'banana'
fruit_tuple = tuple(fruit_list)
print(fruit_tuple) # ('apple', 'pear', 'banana')
删除
当创建的元组不再使用时,可以通过 del 关键字将其删除
''' 元组中的元素值是不允许删除的,但我们可以使用 del 函数来删除整个元组 '''
word_tuple = ('a', 'b', 'c')
del word_tuple
# 当我们使用 del 函数删除某元组后,再使用 print() 函数打印输出时,会报错NameError: name 'word_tuple' is not defined,表明该元组未被定义
元组连接/复制
与字符串一样,元组之间可以使用 +
号和 *
号实现元组的连接和复制,这就意味着它们可以生成一个新的元组
''' 合并 '''
x = (1, 2, 3)
y = (4, 5, 6)
print(x + y) # (1, 2, 3, 4, 5, 6)
''' 复制 '''
x = ('Hello',)
print(x * 5) # ('Hello', 'Hello', 'Hello', 'Hello', 'Hello')
常用方法
count()
# count() - 方法返回指定值在元组中出现的次数
num_tuple = (1, 3, 7, 8, 7, 5, 4, 6, 8, 5, 5)
print(num_tuple.count(5)) # 3
index()
# index() - 方法查找指定值的第一次出现
num_tuple = (1, 3, 7, 8, 7, 5, 4, 6, 8, 5, 5)
print(num_tuple.index(5)) # 5
len()
''' 要确定一个元组有多少项目(元素)时,可以使用len()函数'''
fruit_tuple = ('apple', 'banana', 'cherry')
print(len(fruit_tuple)) # 3
tuple()
''' 将字符串转换为元组 '''
str1 = 'Hello Python'
print(tuple(str1)) # ('H', 'e', 'l', 'l', 'o', ' ', 'P', 'y', 't', 'h', 'o', 'n')
''' 将列表转换为元组 '''
list1 = ['Hello', 'Python']
print(tuple(list1)) # ('Hello', 'Python')
''' 将字典转换为元组 '''
dict1 = {'Hello': 'Python', 'name': 'pink'}
print(tuple(dict1)) # ('Hello', 'name')
''' 将集合转换为元组 '''
set1 = {'Hello', 'Python', 'name', 'pink'}
print(tuple(set1)) # ('pink', 'Python', 'Hello', 'name') 无序
''' 将区间转换为元组 '''
range1 = range(1, 6)
print(tuple(range1)) # (1, 2, 3, 4, 5)
del
元组中的元素值是不允许删除的,但我们可以使用 del 函数来删除整个元组。
word_tuple = ('a', 'b', 'c')
del word_tuple
print(word_tuple) # NameError: name 'word_tuple' is not defined
max()、min()
max() 函数的作用是返回元组中元素最大值。min() 函数的作用是返回元组中元素最小值。
tup1 = (4, 6, 2, 0, -5)
print(max(tup1)) # 6
print(min(tup1)) # -5
tup2 = ('a', 'z', 'A', 'Z')
print(max(tup2)) # z
print(min(tup2)) # A
案例 - 座位随机(1)
"""
现有办公室座位表 seating
先要求从 1号办公室、2号办公室中分别随机抽一个安排到4号办公室去 random 结合 pop() 方法
1. 随机从1号 2号办公室中选取一个人
2. 将其安排到4号办公室去 4号办公室需要自己手动创建的
3. 最后先安排号的作为表打印 append()
"""
import pprint
seating = [
('1号办公室1位置', '戴贵富'),
('1号办公室2位置', '田显余'),
('1号办公室3位置', '李元东'),
('2号办公室1位置', '廖徳超'),
('2号办公室2位置', '秦代坤'),
('2号办公室3位置', '杨久林'),
('3号办公室1位置', '邓永明'),
('3号办公室2位置', '张勇'),
]
# 因为 pop 是有返回值的,那么就可以用一个变量来接收 pop 的返回值,就可以达到随机取值的要求
import random
# 从1号办公室随机取一个人
person1 = seating.pop(random.randint(0, 2)) # randint左右都是闭区间
print(person1)
# 2号办公室随机取一个人
person2 = seating.pop(random.randint(2, 4)) # randint左右都是闭区间
print(person2)
# 手动添加一个 4号 办公室
seat1 = ('4号办公室1位置', person1[1])
seat2 = ('4号办公室2位置', person2[1])
# 添加到列表里面取
seating.append(seat1)
seating.append(seat2)
pprint.pprint(seating)
案例 - 座位随机(2)
'''
有N个人参加会议,现在需要安排座位
请用 python 实现将N个人随机安排座位
提示: pop 和 random.randint 结合
可以导入随机函数模块 random
random.randint(a,b)
在 [a,b] 之间返回一个随机整数,包括 a, b 本身
'''
import random
# 员工
name = """
邓永明 廖徳超 张勇 杨久林 戴贵富 秦代坤 李元东 田显余
"""
# 办公室名字
site_list = ['1号办公室1位置', '1号办公室2位置', '1号办公室3位置',
'2号办公室1位置', '2号办公室2位置', '2号办公室3位置',
'3号办公室1位置', '3号办公室2位置'
]
seating = []
# 将人名分割一个列表
name_list = name.split() # 默认以空白字符分割
print(name_list)
# 人名随机,实现座位随机
for i in range(len(name_list)): # 01234567 控制循环次数
name_index = random.randint(0, len(name_list) - 1) # 通过索引取人名
name_data = name_list.pop(name_index) # 通过 pop 删除有返回值的特性取拿到数据
# print(name_data)
seating.append((site_list[i], name_data))
print(seating)
# 座位随机,实现人随机
for i in range(8): # 01234567 控制循环次数
site_index = random.randint(0, len(site_list) - 1) # 通过索引取人名
site_data = site_list.pop(site_index) # 通过 pop 删除有返回值的特性取拿到数据
seating.append((site_data, name_list[i]))
print(seating)
# 人和座位都进行随机
for i in range(8): # 01234567 控制循环次数
# 人的随机
name_index = random.randint(0, len(name_list) - 1) # 通过索引取人名
name_data = name_list.pop(name_index) # 通过 pop 删除有返回值的特性取拿到数据
# 座位的随机
site_index = random.randint(0, len(site_list) - 1) # 通过索引取人名
site_data = site_list.pop(site_index) # 通过 pop 删除有返回值的特性取拿到数据
# 添加数据
seating.append((site_data, name_data))
print(seating)
案例 - 统计分数范围
''' 假设我们有一组学生的分数,我们希望统计在不同分数范围内的学生人数 '''
scores = (85, 92, 78, 95, 88, 60, 72, 98, 83, 75)
count_low = sum(1 for score in scores if score < 70)
count_medium = sum(1 for score in scores if 70 <= score < 85)
count_high = sum(1 for score in scores if score >= 85)
print(f"低分学生人数:{count_low}") # 低分学生人数:1
print(f"中等分数学生人数:{count_medium}") # 中等分数学生人数:4
print(f"高分学生人数:{count_high}") # 高分学生人数:5
总结
元组作为不可变的序列类型,在Python编程中有着重要的地位。本篇博客介绍了元组的常用函数,包括创建、访问、切片、拼接、复制、长度、最大最小值等操作,同时通过实际案例展示了这些函数的实际应用。在实际编程中,灵活运用元组的函数和特性,可以使代码更加简洁高效,提升开发效率。