← 中文资源

简体中文版本

tuple 打包不可变可哈希记录

tuple 打包定长记录:元素赋值直接 TypeError,可哈希能当字典键;单元素必须带尾逗号,星号解包拆定长头与任意尾。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

x, y = 3 4
lookup by tuple: A1
immutable: 'tuple' object does not support item assignment
single is tuple: True | (42) is: int
head: 1 | rest: [2, 3, 4]

实现说明

各个操作都建立在顶层绑定之上:point、grid、single。

使用要点

  • 每一步打印都带着自己的标签:x, y =、lookup by tuple:、immutable:。

常见问题

运行之前需要装什么吗?

不需要——用到的每个 API 都随语言运行时自带,无需安装。 状态都挂在模块顶层:point、grid、single。

核心语句

except TypeError as exc:
    print("immutable:", exc)

代码示例

# tuple 打包定长记录:不可变、可哈希、可作 dict 键
point = (3, 4)
print("x, y =", point[0], point[1])

# 可哈希:作为字典键给坐标建索引
grid = {point: "A1", (0, 0): "origin"}
print("lookup by tuple:", grid[(3, 4)])

# 不可变:修改元素直接 TypeError
try:
    point[0] = 9
except TypeError as exc:
    print("immutable:", exc)

# 单元素必须带逗号,否则只是加了括号的表达式
single = (42,)
print("single is tuple:", isinstance(single, tuple), "| (42) is:", type(42).__name__)

# 解包与星号收集:定长头 + 任意尾
first, *rest = (1, 2, 3, 4)
print("head:", first, "| rest:", rest)