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
相关推荐
noravinsc7 小时前
关于PEP8
python
DXM05218 小时前
第14期|高阶分割模型:Transformer/SegFormer遥感应用
人工智能·python·神经网络·算法·计算机视觉·cnn·ageo
糖果店的幽灵8 小时前
软件测试接口测试从入门到精通:Python接口自动化 - pytest测试框架
软件测试·python·功能测试·自动化·pytest·接口测试
swordbob8 小时前
CAP 定理:为什么不能同时实现 C、A、P?
开发语言·后端·spring
疯狂成瘾者8 小时前
Java 常用工具包 java.util
java·开发语言·windows
枫叶丹48 小时前
【HarmonyOS 6.0】MDM Kit 新特性:PC/2in1设备无锁屏密码重启自动解锁能力详解
开发语言·华为·harmonyos
程序员龙叔8 小时前
从 0 开始学习 AI 测试 - 从接口测试来教你如何用 AI 来生成自动化测试代码
自动化测试·软件测试·python·软件测试工程师·测试工具·性能测试·ai测试
ZHW_AI课题组8 小时前
Python 调用百度智能云 API 实现地址识别
开发语言·人工智能·python·机器学习·百度·数据挖掘
88号技师8 小时前
2026年2月一区SCI-交叉传播优化算法Propagation Alongside Crossover-附Matlab免费代码
开发语言·算法·数学建模·matlab·优化算法
A.零点8 小时前
【2个月 C 语言从入门到精通:零基础系统教程】第十二讲:深入了解指针(五)
c语言·开发语言·网络·笔记·visual studio