Match (匹配)
官方文档:https://docs.python.org/zh-cn/3.12/reference/compound_stmts.html
match value:
case pattern1:
...
case pattern2:
...
case _:
...
- match 类似 switch
- case _ 类似 default
match status:
case 200:
print("OK")
case 404:
print("Not Found")
case _:
print("Unknown")
match ext:
case "jpg" | "png" | "gif":
print("图片文件")
case "mp4" | "avi":
print("视频文件")
match x:
case x if x > 10:
print("> 10")
case x if x == 10:
print("= 10")
case _:
print("< 10")
固定长度
match items:
case [x, y]:
print("两个元素", x, y)
可变数量(*rest)
match items:
case [first, *rest]:
print(first, rest)
match data:
case {"code": c, "name": n}:
print(c, n)
部分匹配也行:
match data:
case {"code": c}:
print("code =", c)
class User:
def __init__(self, name):
self.name = name
user = User("tom")
match user:
case User(name=username):
print("用户名字:", username)
这是 自动解构类实例 – 非常强。
match value:
case _:
print("fallback")
| 场景 | 用 match-case | | 有多个离散值分支 | ✅ | | 结构化数据(dict / list)匹配 | ✅(强烈推荐) | | 拆解类对象 | ✅ | | 复杂条件判断 | ✅ | | 简单条件(<、>、逻辑判断) | if 更好 |
match target:
case "up_pool":
info = "涨停池"
case "continuous_up_pool":
info = "连板池"
case "up_open_pool":
info = "炸板池"
case "down_pool":
info = "跌停池"
case _:
raise ValueError(f"未知 target: {target}")
之前写的 match True: case True if ...: 不太 Pythonic,最好改成上面这种。
def build_filter(expr: dict):
match expr:
case {"field": field, "op": "eq", "value": v}:
return f"{field} = %s", [v]
case {"field": field, "op": "gt", "value": v}:
return f"{field} > %s", [v]
case {"field": field, "op": "in", "value": list(values)}:
return f"{field} IN ({','.join(['%s']*len(values))})", values
case _:
raise ValueError("无效表达式")
match data:
case {"user": {"name": name, "age": age}}:
print(name, age)
比手动写判断干净太多。
match user:
case {"age": age} if age >= 18:
print("adult")
case {"age": age}:
print("child")
这是 match 的最强部分之一。
❌ 不能写表达式
错误:
case x > 10:
正确:
case x if x > 10:
❌ 匹配顺序重要(按顺序执行)
🟦 14. 快速速查表(收藏)
| 功能 | 写法 |
|---|---|
| 多分支 | match x: case 1: … |
| default | case _: |
| 多模式 | `case “a” |
| 列表解构 | case [a, b]: |
| 列表剩余 | case [a, *rest]: |
| dict 匹配 | case {“a”: x}: |
| 类匹配 | case Class(attr=x): |
| case 守卫 | case x if x > 10: |
| 嵌套匹配 | case {“u”: {“name”: n}}: |