Python3 入门教程
模式匹配(match-case,3.10+)
本教程共 70 篇 · 第 17 篇 · 更新于 2026-07-22 · 约 3 分钟阅读
PythonPython3 入门教程模式匹配match-case结构化匹配守卫子句
17. 模式匹配(match-case,3.10+)
本节目标:掌握 Python 3.10 引入的 match-case 语法,用它替代冗长的 if-elif 链。
为什么要学 match-case
以前写多分支判断,只能长串的 if-elif:
if status == 200:
print("成功")
elif status == 404:
print("未找到")
elif status == 500:
print("服务器错误")
else:
print("未知状态")
Python 3.10 引入了 match-case,让这种场景更简洁、更有表现力。
Note如果你的 Python 版本低于 3.10,这一节的代码跑不了。命令行输入
python --version确认一下。
基本用法
status = 404
match status:
case 200:
print("成功")
case 404:
print("未找到")
case 500:
print("服务器错误")
case _:
print("未知状态")
case _ 是通配符,匹配一切,相当于 switch-case 里的 default。
匹配多个值
用 | 表示「或」:
match status:
case 200 | 201:
print("成功")
case 400 | 401 | 403 | 404:
print("客户端错误")
case 500 | 502 | 503:
print("服务器错误")
case _:
print("其他")
匹配数据结构
match-case 最强大的地方不是替代 if-elif,而是解构数据结构。
匹配元组
point = (3, 4)
match point:
case (0, 0):
print("原点")
case (x, 0):
print(f"x 轴上,x = {x}")
case (0, y):
print(f"y 轴上,y = {y}")
case (x, y):
print(f"点 ({x}, {y})")
变量 x 和 y 在匹配时自动绑定。如果 point 是 (3, 4),会匹配到最后一个 case,x 变成 3,y 变成 4。
匹配列表
items = [1, 2, 3]
match items:
case []:
print("空列表")
case [single]:
print(f"只有一个元素: {single}")
case [first, *rest]:
print(f"首元素: {first}, 其余: {rest}")
匹配字典
user = {"name": "Alice", "age": 25}
match user:
case {"name": str(name), "age": int(age)}:
print(f"{name}, {age} 岁")
case {"name": str(name)}:
print(f"{name}, 年龄未知")
case _:
print("格式不对")
Tip字典匹配不要求键完全相等,只匹配列出的键。上面的
user如果多一个"city"键,仍然能匹配第一个 case。
匹配类实例(dataclass)
from dataclasses import dataclass
@dataclass
class Point:
x: int
y: int
p = Point(1, 2)
match p:
case Point(x=0, y=0):
print("原点")
case Point(x=x, y=0):
print(f"x 轴上,x = {x}")
case Point(x=0, y=y):
print(f"y 轴上,y = {y}")
case Point(x=x, y=y):
print(f"点 ({x}, {y})")
守卫子句(guard)
在 case 后面加 if 进一步过滤:
match age:
case n if n < 0:
print("年龄不能为负")
case n if n < 18:
print("未成年")
case n if n < 60:
print("成年人")
case _:
print("老年人")
match-case vs if-elif
| 场景 | 推荐 |
|---|---|
| 简单值判断 | 两者都行 |
| 数据结构解构 | match-case |
| 复杂条件运算 | if-elif |
| 需要守卫子句 | match-case |
match-case 不是来取代 if 的,而是填补 Python 在结构化模式匹配上的空白。处理 JSON、AST、消息分发等场景时,它比 if-elif 优雅得多。
来源:参考了 runoob「Python3 条件控制」中的 match-case 部分、Python 官方文档(PEP 634)等,改写后所得。