【Python基础篇】【10.数据类型 - 元组 tuple】创建、取值、删除、修改、常用方法、案例等详细笔记


元组 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编程中有着重要的地位。本篇博客介绍了元组的常用函数,包括创建、访问、切片、拼接、复制、长度、最大最小值等操作,同时通过实际案例展示了这些函数的实际应用。在实际编程中,灵活运用元组的函数和特性,可以使代码更加简洁高效,提升开发效率。

  • 11
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
Python中,你可以使用不同的方式来实现数据结构。下面是一些常见的数据结构及其示例代码: 1. 列表(List):有序的可变容器,可以存储各种类型的元素。 ```python # 创建一个列表 my_list = [1, 2, 3, 'a', 'b', 'c'] # 添加元素到列表末尾 my_list.append(4) # 访问列表中的元素 print(my_list[0]) # 输出:1 # 修改列表中的元素 my_list[3] = 'd' # 删除列表中的元素 del my_list[2] ``` 2. 元组Tuple):有序的不可变容器,可以存储各种类型的元素。 ```python # 创建一个元组 my_tuple = (1, 2, 3, 'a', 'b', 'c') # 访问元组中的元素 print(my_tuple[0]) # 输出:1 # 元组是不可变的,因此不能修改删除元组中的元素 ``` 3. 字典(Dictionary):无序的键值对集合,每个元素由一个键和一个值组成。 ```python # 创建一个字典 my_dict = {'name': 'John', 'age': 25, 'city': 'New York'} # 访问字典中的值 print(my_dict['name']) # 输出:John # 修改字典中的值 my_dict['age'] = 26 # 添加新的键值对 my_dict['occupation'] = 'Engineer' # 删除字典中的键值对 del my_dict['city'] ``` 4. 集合(Set):无序且不重复的元素集合。 ```python # 创建一个集合 my_set = {1, 2, 3, 4, 5} # 添加元素到集合 my_set.add(6) # 从集合中移除元素 my_set.remove(3) # 计算两个集合的交集、并集、差集等 set1 = {1, 2, 3} set2 = {3, 4, 5} intersection = set1.intersection(set2) # 交集 union = set1.union(set2) # 并集 difference = set1.difference(set2) # 差集 ``` 这只是数据结构的简单示例,Python还提供了其他一些数据结构和细致的操作方法。通过使用这些数据结构,你可以更好地组织和处理数据。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

My.ICBM

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值