Python 元组函数
上次修改时间:2025 年 4 月 11 日
这份全面的指南探讨了 Python 的 tuple
函数,该函数创建不可变的序列对象。我们将介绍创建、从其他可迭代对象转换以及在 Python 程序中使用元组的实际示例。
基本定义
tuple
函数创建一个新的元组对象。它可以将其他可迭代对象转换为元组或创建空元组。元组是不可变的、有序的集合,可以包含任何 Python 对象。
主要特点:不可变序列,有序元素,可以包含异构类型,支持索引和切片,如果所有元素都可哈希,则可以哈希。
创建空元组和单元素元组
这是基本用法,展示了如何创建空元组和包含一个元素的元组(请注意单元素元组的逗号要求)。
# Empty tuple empty = tuple() print(empty) # () print(type(empty)) # <class 'tuple'> # Single-element tuple (note comma) single = tuple([42]) # Using iterable single2 = (42,) # Using literal print(single) # (42,) print(single2) # (42,)
此示例展示了创建空元组的两种方法以及单元素元组的重要逗号要求。如果没有逗号,Python 会将括号解释为分组运算符。
没有参数的 tuple()
调用会创建一个空元组,与字面量 ()
相同。 对于单个元素,逗号使其成为元组。
将其他可迭代对象转换为元组
tuple
函数可以将任何可迭代对象转换为元组。 此示例演示了从列表、字符串和字典的转换。
# From list numbers = [1, 2, 3] tuple_numbers = tuple(numbers) print(tuple_numbers) # (1, 2, 3) # From string text = "hello" tuple_chars = tuple(text) print(tuple_chars) # ('h', 'e', 'l', 'l', 'o') # From dictionary (gets keys) person = {'name': 'Alice', 'age': 25} tuple_keys = tuple(person) print(tuple_keys) # ('name', 'age')
这显示了 tuple
如何转换各种可迭代对象。 列表变为具有相同元素的元组。 字符串变为字符元组。
字典默认转换为其键的元组。 要获取键值对,请使用 person.items()
作为可迭代对象。
元组解包和函数参数
元组通常用于解包多个值和处理可变函数参数。 此示例演示了这两种模式。
# Tuple unpacking coordinates = (10.5, 20.3) x, y = coordinates print(f"x: {x}, y: {y}") # x: 10.5, y: 20.3 # Variable arguments def print_args(*args): print(tuple(args)) print_args(1, 2, 3) # (1, 2, 3)
元组解包允许从元组一次性分配多个变量。 *args
语法将位置参数收集到元组中。
这些模式在 Python 中很常见,用于简洁的多值处理和创建灵活的函数接口。
不可变特性
此示例通过显示允许哪些操作以及哪些操作会引发异常来演示元组的不可变性。
colors = tuple(['red', 'green', 'blue']) # Allowed operations print(colors[1]) # 'green' (indexing) print(colors[:2]) # ('red', 'green') (slicing) print(len(colors)) # 3 try: colors[1] = 'yellow' # Attempt modification except TypeError as e: print(f"Error: {e}") # 'tuple' object does not support item assignment
元组支持所有不修改它们的操作,例如索引、切片和长度检查。 尝试修改元素会引发 TypeError。
这种不可变性使得元组可用作字典键(当所有元素都可哈希时)以及用于存储不应更改的常量数据。
与列表的性能比较
此示例比较了元组和列表在创建和迭代方面的性能,显示了元组在某些场景中的优势。
import timeit # Creation time list_time = timeit.timeit('x = [1, 2, 3, 4, 5]', number=1000000) tuple_time = timeit.timeit('x = (1, 2, 3, 4, 5)', number=1000000) print(f"List creation: {list_time:.3f}") print(f"Tuple creation: {tuple_time:.3f}") # Iteration time list_iter = timeit.timeit('for i in x: pass', 'x = [1, 2, 3, 4, 5]', number=1000000) tuple_iter = timeit.timeit('for i in x: pass', 'x = (1, 2, 3, 4, 5)', number=1000000) print(f"List iteration: {list_iter:.3f}") print(f"Tuple iteration: {tuple_iter:.3f}")
由于元组的不可变性,通常比列表创建得更快。 迭代速度相似,但对于固定集合,元组具有内存优势。
对异构的、不变的数据使用元组,对同构的、可修改的集合使用列表。
最佳实践
- 用于固定数据: 对于不会更改的集合,首选元组
- 作为字典键: 使用元组(带有可哈希元素)作为键
- 函数返回值: 将多个值作为元组返回
- 内存效率: 对于大型常量序列,使用元组
- 文档意图: 使用元组来表示不可变数据
资料来源
作者
列出所有 Python 教程。