首页 › Python 数据结构 › 元组 tuple

元组 tuple

元组和列表类似,但创建后不能修改,用圆括号表示:

point = (3, 4)
rgb = (255, 128, 0)
single = (42,)      # 只有一个元素时必须加逗号

为什么需要元组

解包

x, y = point
print(x, y)            # 3 4

first, *rest = (1, 2, 3, 4)
print(first, rest)     # 1 [2, 3, 4]

a, b = 1, 2
a, b = b, a            # 交换两个变量

具名元组

当元组字段较多时,用 collections.namedtuple 可以按名字访问,代码更易读:

from collections import namedtuple

User = namedtuple("User", ["name", "age"])
u = User("小明", 20)
print(u.name, u.age)

练习题

学完本节后,试着独立完成下面的练习,再展开参考答案对照。

练习 1 用元组表示平面上的点,编写函数计算两点间的距离。

查看参考答案
import math

def distance(p, q):
    (x1, y1), (x2, y2) = p, q
    return math.hypot(x2 - x1, y2 - y1)

print(distance((0, 0), (3, 4)))
参考输出:
5.0

练习 2 有一组 (姓名, 年龄) 元组,按年龄从小到大排序,年龄相同时按姓名排序。

查看参考答案
people = [("Tom", 25), ("Amy", 30), ("Bob", 25)]
print(sorted(people, key=lambda p: (p[1], p[0])))
参考输出:
[('Bob', 25), ('Tom', 25), ('Amy', 30)]