Skip to main content
Documents
Toggle Dark/Light/Auto mode Toggle Dark/Light/Auto mode Toggle Dark/Light/Auto mode Back to homepage

Match (匹配)

官方文档:https://docs.python.org/zh-cn/3.12/reference/compound_stmts.html

🟦 1. 基础语法

match value:
    case pattern1:
        ...
    case pattern2:
        ...
    case _:
        ...
  • match 类似 switch
  • case _ 类似 default

🟩 2. 最简单示例

match status:
    case 200:
        print("OK")
    case 404:
        print("Not Found")
    case _:
        print("Unknown")

🟦 3. case 支持多模式 | 或匹配

match ext:
    case "jpg" | "png" | "gif":
        print("图片文件")
    case "mp4" | "avi":
        print("视频文件")

🟩 4. case 中直接进行条件判断(好用)

match x:
    case x if x > 10:
        print("> 10")
    case x if x == 10:
        print("= 10")
    case _:
        print("< 10")

🟦 5. 匹配序列(列表/元组)

固定长度

match items:
    case [x, y]:
        print("两个元素", x, y)

可变数量(*rest)

match items:
    case [first, *rest]:
        print(first, rest)

🟩 6. 匹配 dict(工程中很常用)

match data:
    case {"code": c, "name": n}:
        print(c, n)

部分匹配也行:

match data:
    case {"code": c}:
        print("code =", c)

🟦 7. 匹配类对象(比 isinstance 强太多)

class User:
    def __init__(self, name):
        self.name = name

user = User("tom")

match user:
    case User(name=username):
        print("用户名字:", username)

这是 自动解构类实例 – 非常强。

🟩 8. 默认分支(用 _ )

match value:
    case _:
        print("fallback")

🟦 9. match-case vs if-elif:什么时候用?

| 场景 | 用 match-case | | 有多个离散值分支 | ✅ | | 结构化数据(dict / list)匹配 | ✅(强烈推荐) | | 拆解类对象 | ✅ | | 复杂条件判断 | ✅ | | 简单条件(<、>、逻辑判断) | if 更好 |

🟩 10. 工程应用示例(你的项目里常用)

① API 类型分发(比 if-elif 好看 100 倍)

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,最好改成上面这种。

② SQL 构造器(dict 自动解析)

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("无效表达式")

🟦 11. 高级:嵌套结构匹配

match data:
    case {"user": {"name": name, "age": age}}:
        print(name, age)

比手动写判断干净太多。

🟩 12. 高级:使用守卫(case 中 if)

match user:
    case {"age": age} if age >= 18:
        print("adult")
    case {"age": age}:
        print("child")

这是 match 的最强部分之一。

🟦 13. match-case 禁忌(容易踩坑)

❌ 不能写表达式

错误:

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}}: