Python 中的 match-case(模式匹配)

match-case 是 Python 3.10 引入的一种结构化的模式匹配 语法,功能类似于其他语言中的 switch-case,但远比它强大和灵活 。它不仅仅是值的匹配,而是基于结构的匹配。

一、基本语法:值的匹配

最简单的用法就是匹配一个变量的值。

复制代码
def http_status(code):
    match code:
        case 200:
            return "OK"
        case 404:
            return "Not Found"
        case 500:
            return "Internal Server Error"
        case _:
            return "Unknown Status"

print(http_status(404))  # Not Found

这里的 _ 是通配符,匹配所有未被前面 case 捕获的情况(类似于其他语言的 default)。

二、匹配字面量、变量和类型

1. 匹配多个值(使用 | 表示或)

复制代码
def get_weekday(num):
    match num:
        case 1 | 7:
            return "周末"
        case 2 | 3 | 4 | 5 | 6:
            return "工作日"
        case _:
            return "无效数字"

2. 匹配变量,并捕获值

可以用 case 中的变量来"捕获"匹配到的值,供后续使用。注意:变量名必须是大写 (如 CODE),否则会和通配符混淆(但实际规则更细一些)。

复制代码
def handle_code(code):
    match code:
        case 200:
            print("成功")
        case CODE:   # 这里匹配任意值,并赋值给 CODE
            print(f"未知状态码: {CODE}")

3. 匹配类型(使用 case 配合 isinstance 的语法糖)

注意:这里不是直接写类名,而是使用"类模式",写法类似构造函数。

复制代码
def process_value(value):
    match value:
        case int():
            print("这是一个整数")
        case str():
            print("这是一个字符串")
        case list():
            print("这是一个列表")
        case _:
            print("其他类型")

三、解构模式

这是 match-case 真正强大的地方:可以解构数据,匹配内部结构并提取数据。

1. 匹配序列(列表/元组)

复制代码
def process_point(point):
    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={x}, y={y}")
        case _:
            print("不是二维点")

process_point([0, 5])   # 在 Y 轴上,y=5

2. 匹配字典

复制代码
def handle_json(data):
    match data:
        case {"type": "user", "name": name, "age": age}:
            print(f"用户: {name}, 年龄: {age}")
        case {"type": "product", "name": name, "price": price}:
            print(f"产品: {name}, 价格: {price}")
        case _:
            print("未知数据结构")

3. 匹配对象(类实例)

复制代码
class Point:
    __match_args__ = ("x", "y")
    def __init__(self, x, y):
        self.x = x
        self.y = y

def process_point(p):
    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={x}, y={y}")

四、与 switch-case 的区别

match-case 和传统的 switch-case 看起来像,但本质不同:

特性 match-case 传统 switch-case
支持解构 是 否
匹配类型 支持 不支持
通配符 _ default
多值匹配 `case 1 2`
匹配模式 模式匹配 值匹配
相关推荐
BD_Marathon3 小时前
安装Jupyter notebook
ide·python·jupyter
Zlzxzw3 小时前
End-to-End Autonomous Generation of Human Assembly Plans
python
Wellijohn3 小时前
2000 个请求、30% 失败率:我把 Python 批量并发的限流和重试参数算了一遍
后端·python·性能优化
Logintern095 小时前
deep agents 多智能体模式——规划与委派
python·langchain
2601_967980117 小时前
Python 办公自动化合集 ⑰:Excel自动计算——总和/平均分/最大值
python·pycharm·办公自动化·数据处理·excel自动计算
databook9 小时前
时间序列预测,模型换了一圈为什么没变好
python·数据分析
reasonsummer9 小时前
【教学类-07-17】20261119大3班破译电话号码HTML实际操作(添加“跳过按钮”和“返回按钮”在底部、增加“自编题目+解题”部分)
python·html
2601_9679801113 小时前
Python闭包(Closure)详解
python·作用域·装饰器·函数式编程·闭包
AI创界者13 小时前
ComfyUI 进阶实战:MiniMax-H3 视频人物脸部替换工作流全解析(对比 Face 5.5 实测与避坑指南)
人工智能·python·aigc
承渊政道13 小时前
【Python编程快速上手—让繁琐工作自动化】(模式匹配与正则表达式:从找到一个号码到批量提取信息)
python·正则表达式·pycharm·自动化·模式匹配