元组就像数据的"保险箱":
模块 | 功能 | 时间复杂度 |
---|---|---|
索引访问 | 获取元素 | O(1) |
切片操作 | 获取子元组 | O(k) |
哈希计算 | 生成哈希值 | O(n) |
内存结构 | 固定大小存储 | 比列表少1指针 |
特性 | 元组 | 列表 | 命名元组 |
---|---|---|---|
可变性 | ❌ | ✔️ | ❌ |
哈希支持 | ✔️ | ❌ | ✔️ |
字段命名 | ❌ | ❌ | ✔️ |
内存占用 | 低 | 高 | 中等 |
# Python 3.7+ 原生支持
from collections import namedtuple
# 创建元组
point = (10, 20)
print(point[0]) # 输出:10(索引从0开始)
# 空元组
empty = ()
# 坐标解包
x, y = (30, 40)
print(f"X: {x}, Y: {y}") # X: 30, Y: 40
# 扩展解包
first, *rest = (1, 2, 3, 4)
print(rest) # [2, 3, 4]
# 坐标作为字典键
locations = {
(35.6895, 139.6917): "Tokyo",
(40.7128, -74.0060): "New York"
}
print(locations[(35.6895, 139.6917)]) # Tokyo
def get_stats(numbers):
return min(numbers), max(numbers), sum(numbers)/len(numbers)
min_val, max_val, avg_val = get_stats([1, 2, 3])
try:
colors = ('red', 'green')
colors[0] = 'blue' # 触发TypeError
except TypeError as e:
print(e) # 'tuple' object does not support item assignment
User = namedtuple('User', ['name', 'age', 'email'])
admin = User('Alice', 30, '[email protected]')
print(admin.email) # [email protected]
from typing import Tuple
def get_coordinates() -> Tuple[float, float]:
return (35.6895, 139.6917)
info = ('Alice', 30)
print("Name: %s, Age: %d" % info) # 自动解包
# 模拟数据库返回
records = [
(1, 'Alice', 'Engineer'),
(2, 'Bob', 'Designer')
]
for id, name, role in records:
print(f"{name}: {role}")
def cached(func):
cache = {}
def wrapper(*args):
key = tuple(args) # 转换为可哈希类型
if key not in cache:
cache[key] = func(*args)
return cache[key]
return wrapper
@cached
def factorial(n):
return 1 if n <= 1 else n * factorial(n-1)
# 案例5输出:
'tuple' object does not support item assignment
# 案例6输出:
[email protected]
# 案例10输出:
factorial(5) => 120(缓存生效)
操作 | 元组 | 列表 | 优势比 |
---|---|---|---|
创建时间 | 12ms | 15ms | 快25% |
内存占用 | 8MB | 10MB | 节省20% |
迭代速度 | 18ms | 20ms | 快10% |
配置信息存储
DB_CONFIG = ('localhost', 3306, 'user', 'pass')
枚举替代方案
StatusCodes = (
('OK', 200),
('NOT_FOUND', 404)
)
数据记录处理
for record in cursor.fetchall(): # 数据库返回元组
process(record)
版本号管理
__version__ = (2, 1, 3)
函数参数验证
def draw_line(start: tuple, end: tuple):
assert len(start) == 2 and len(end) == 2
缓存键生成
cache_key = tuple(sorted(params.items()))
类型安全数据
Vector3D = tuple[float, float, float]
API响应包装
return (True, result) # 状态+数据
不变配置传递
def init(config: tuple):
# 确保配置不被修改
模式匹配
match point:
case (0, 0):
print("原点")
case (x, 0):
print(f"X轴坐标:{x}")
尝试修改元素
colors = ('red', 'green')
colors[0] = 'blue' # TypeError
单元素元组漏写逗号
singleton = (1) # 不是元组
correct = (1,) # 正确写法
可变元素陷阱
items = ([1,2], [3,4])
items[0].append(3) # 合法但可能引发意外修改
错误解包
a, b = (1, 2, 3) # ValueError
误用列表方法
nums = (1, 2)
nums.append(3) # AttributeError
哈希不可哈希元素
bad_key = ([1,2], 3) # 无法作为字典键
性能误判
# 频繁创建小元组可能不如列表高效
深度不可变性误解
matrix = ((1, [2]), (3, 4)) # 内部列表仍可变
类型检查错误
isinstance((1,2), list) # 始终False
内存回收误解
del big_tuple # 不会立即释放内存
类型验证
assert isinstance(config, tuple), "需要元组参数"
不可变检查
from copy import deepcopy
try:
deepcopy(nested_tuple)
except TypeError:
print("包含不可深拷贝对象")
内存分析
import sys
print(sys.getsizeof((1,2,3))) # 查看内存占用