python---元组(Tuple)

文章目录

元组是Python中的一种内置数据类型,它是一个不可变(immutable)、有序的序列。元组用圆括号()表示,元素之间用逗号分隔。

基本特性

1、不可变性:一旦创建,元组的内容不能修改(不能添加、删除或更改元素)

2、有序性:元素按照插入顺序存储,可以通过索引访问

3、可包含任意类型:可以包含数字、字符串、列表、甚至其他元组等

4、允许重复元素

创建元组

创建元组时,如果只有一个元素,后面不加逗号,则不是元组类型。例如not_a_tuple = (5)为整数型,not_a_tuple = ('c')为字符串型

bash 复制代码
# 空元组
empty_tuple = ()
print(f"empty_tuple is {empty_tuple}")

# 包含元素的元组
numbers = (1, 2, 3, 4)
fruits = ('apple', 'banana', 'cherry')
print(f"numbers is {numbers}")
print(f"fruits is {fruits}")

# 只有一个元素的元组(注意末尾的逗号)
single_element = (5,)  # 这是一个元组
print(f"single_element is {single_element}", "type of single_element is", type(single_element))
not_a_tuple = (5)      # 这不是元组,只是一个整数
print(f"not_a_tuple is {not_a_tuple}", "type of not_a_tuple is", type(not_a_tuple))

# 不使用括号创建(元组打包)
colors = 'red', 'green', 'blue'
print(f"colors is {colors}")

访问元组元素

bash 复制代码
t = ('a', 'b', 'c', 'd', 'e')

# 通过索引访问
print(t[0])   # 'a'
print(t[2])   # 'c'

# 负索引
print(t[-1])  # 'e'(最后一个元素)

# 切片
print(t[1:3]) # ('b', 'c')

元组操作

bash 复制代码
# 连接元组
tuple1 = (1, 2, 3)
tuple2 = ('a', 'b')
combined = tuple1 + tuple2  # (1, 2, 3, 'a', 'b')

# 重复元组
repeated = tuple1 * 2  # (1, 2, 3, 1, 2, 3)

# 成员检查
print(2 in tuple1)  # True
print('x' in tuple1) # False

# 长度
print(len(tuple1))  # 3

元组解包(Unpacking)

基本解包

point = (10, 20)

x, y = point

print(x) # 10

print(y) # 20

使用*收集剩余元素

bash 复制代码
numbers = (1, 2, 3, 4, 5)
first, *middle, last = numbers
print(first)   # 1
print(middle)  # [2, 3, 4](注意变成了列表)
print(last)    # 5

# 交换变量 不适用括号创建元组
a, b = 1, 2
a, b = b, a    # 交换a和b的值
print(f"a = {a}, b = {b}")

元组方法

由于元组不可变,它只有两个方法:

1、count() - 返回指定值出现的次数

2、index() - 返回指定值的第一个索引

注意:元组没有增删改查的方法。

bash 复制代码
t = (1, 2, 3, 2, 4, 2)

print(t.count(2))  # 3
print(t.index(3))  # 2

元组与列表的比较

特性 元组 (Tuple) 列表 (List)
可变性 不可变 可变
语法 使用() 使用[]
性能 更快 较慢
内存使用 更少 较多
安全性 更安全 较不安全

使用场景

1、当需要确保数据不被修改时(如常量集合)

2、作为字典的键(因为元组不可变,而列表不能作为键)

3、函数返回多个值时(实际上返回的是一个元组)

4、性能敏感的场景(元组比列表更高效)

c 复制代码
# 函数返回多个值(实际上是返回一个元组)
def get_stats(numbers):
    return min(numbers), max(numbers), sum(numbers)/len(numbers)

# 字典中使用元组作为键
locations = {
    (35.6895, 139.6917): "Tokyo",
    (40.7128, -74.0060): "New York"
}

元组嵌套

bash 复制代码
t = (1, (2, 3), (4, (5, 6)))
print(t[1])        # 输出: (2, 3)
print(t[1][0])     # 输出: 2
print(t[2][1][0])  # 输出: 5
相关推荐
lixzest2 小时前
快速梳理遗留项目
java·c++·python
xnglan3 小时前
使用爬虫获取游戏的iframe地址
开发语言·爬虫·python·学习
zhysunny3 小时前
04.建造者模式的终极手册:从快餐定制到航天飞船的组装哲学
java·开发语言·建造者模式
郝学胜-神的一滴3 小时前
建造者模式:构建复杂对象的优雅方式
开发语言·c++·程序人生·建造者模式
AAIshangyanxiu3 小时前
最新基于R语言结构方程模型分析与实践技术应用
开发语言·r语言·结构方程模型·生态统计学
cwn_4 小时前
Sequential 损失函数 反向传播 优化器 模型的使用修改保存加载
人工智能·pytorch·python·深度学习·机器学习
老鱼说AI4 小时前
Transformer Masked loss原理精讲及其PyTorch逐行实现
人工智能·pytorch·python·深度学习·transformer
lxmyzzs4 小时前
【已解决】YOLO11模型转wts时报错:PytorchStreamReader failed reading zip archive
人工智能·python·深度学习·神经网络·目标检测·计算机视觉·bug
Fly-ping5 小时前
【前端】JavaScript 的事件循环 (Event Loop)
开发语言·前端·javascript
范纹杉想快点毕业5 小时前
基于C语言的Zynq SOC FPGA嵌入式裸机设计和开发教程
c语言·开发语言·数据库·嵌入式硬件·qt·fpga开发·嵌入式实时数据库