当前位置:

首页 > 编程开发 > Python基础指南之match-case模式匹配语句的使用教学

Python基础指南之match-case模式匹配语句的使用教学

Python3.10引入的match-case语句支持结构化模式匹配,可匹配序列、映射和类实例,通过变量绑定、守卫条件和嵌套解构,支持通配符、常量匹配及类型检查,提供比传统switch更强大、更灵活且更易读的分支处理能力,显著增强Python控制流。

本文目录

    一、开篇:Python 3.10的里程碑特性

    2021年10月,Python 3.10正式发布,其中最引人注目的新特性就是结构化模式匹配(Structural Pattern Matching)——也就是match-case语句。它绝不是switch的简单翻版,而是比switch强大得多的一种模式匹配工具。

    Python基础指南之match-case模式匹配语句的使用教学

    先看看它长什么样:

    # 经典的使用场景:根据状态码返回消息
    def http_status_message(code):
        match code:
            case 200:
                return "OK"
            case 404:
                return "Not Found"
            case 500:
                return "Internal Server Error"
            case _:
                return "Unknown"
    

    这段代码看起来确实像其他语言的switch-case。但match-case的能力远不止于此——它能够匹配数据结构、解构对象、使用守卫条件,甚至能匹配自定义类的实例。接下来,我们从基础到高级,全面拆解这个Python新利器。

    版本要求

    # match-case 需要 Python 3.10+
    import sys
    print(f"Python版本: {sys.version}")
    
    # 检查是否支持match-case
    if sys.version_info >= (3, 10):
        print("✅ 支持 match-case")
    else:
        print("❌ 请升级到 Python 3.10 或更高版本")
    

    二、match-case 基础语法

    2.1 最简单的模式匹配

    # 基本语法
    # match subject:
    #     case pattern1:
    #         action1()
    #     case pattern2:
    #         action2()
    #     case _:
    #         default_action()
    
    # 示例:星期几
    def what_day(day):
        match day:
            case 1:
                return "星期一"
            case 2:
                return "星期二"
            case 3:
                return "星期三"
            case 4:
                return "星期四"
            case 5:
                return "星期五"
            case 6:
                return "星期六"
            case 7:
                return "星期日"
            case _:          # _ 是通配符,匹配任何值
                return "无效的日期数字"
    
    print(what_day(1))    # 星期一
    print(what_day(7))    # 星期日
    print(what_day(0))    # 无效的日期数字
    
    # 关于 _ 通配符
    # _ 是一个特殊的"吸尘器"模式,匹配一切
    # 不同于变量名(变量名会绑定值),_ 不会绑定
    

    2.2 匹配多个值(OR模式)

    # 使用 | 匹配多个值
    def classify_number(n):
        match n:
            case 0:
                return "零"
            case 1 | 2 | 3:
                return "小数字(1-3)"
            case 4 | 5 | 6:
                return "中数字(4-6)"
            case 7 | 8 | 9:
                return "大数字(7-9)"
            case _:
                return "超出范围"
    
    for i in range(11):
        print(f"{i}: {classify_number(i)}")
    
    # 可用于合并相似的处理逻辑
    def is_weekend(day):
        match day.lower():
            case "saturday" | "sunday":
                return True
            case "monday" | "tuesday" | "wednesday" | "thursday" | "friday":
                return False
            case _:
                return None
    

    2.3 匹配时的变量绑定

    这是match-case超越switch的关键特性之一:

    # match-case可以在匹配时提取值
    def process_command(command):
        match command.split():
            case ["quit"]:
                print("退出程序")
            case ["hello"]:
                print("你好!")
            case ["add", x]:           # x 绑定到第二个元素
                print(f"加上 {x}")
            case ["add", x, y]:        # x, y 分别绑定
                print(f"{x} + {y} = {int(x) + int(y)}")
            case _:
                print("未知命令")
    
    process_command("quit")          # 退出程序
    process_command("add 10")        # 加上 10
    process_command("add 10 20")     # 10 + 20 = 30
    process_command("unknown xyz")   # 未知命令
    

    三、结构化模式匹配(核心特性)

    3.1 匹配序列(列表/元组)

    # 匹配不同长度和内容的序列
    def analyze_sequence(seq):
        match seq:
            case []:
                return "空序列"
            case [x]:
                return f"单元素序列: {x}"
            case [x, y]:
                return f"两元素序列: {x}, {y}"
            case [x, y, z]:
                return f"三元素序列: {x}, {y}, {z}"
            case [first, *rest]:      # *rest 收集剩余元素
                return f"首元素: {first}, 剩余: {rest}"
            case _:
                return "不是序列"
    
    print(analyze_sequence([]))               # 空序列
    print(analyze_sequence([42]))             # 单元素序列: 42
    print(analyze_sequence([1, 2]))           # 两元素序列: 1, 2
    print(analyze_sequence([1, 2, 3, 4, 5])) # 首元素: 1, 剩余: [2, 3, 4, 5]
    
    # * 也可以出现在中间
    def extract_parts(seq):
        match seq:
            case [first, *middle, last]:
                return f"首={first}, 中={middle}, 尾={last}"
            case _:
                return "太短了"
    
    print(extract_parts([1, 2, 3, 4, 5]))  # 首=1, 中=[2, 3, 4], 尾=5
    print(extract_parts([1, 2]))           # 首=1, 中=[], 尾=2
    print(extract_parts([1]))              # 太短了
    

    3.2 匹配映射(字典)

    # 匹配字典结构
    def analyze_config(config):
        match config:
            case {"host": host, "port": port}:
                return f"服务器: {host}:{port}"
            case {"host": host, "port": port, "debug": debug}:
                return f"服务器: {host}:{port}, 调试={'开' if debug else '关'}"
            case {"database": db_config}:
                return f"数据库配置: {db_config}"
            case {}:
                return "空配置"
            case _:
                return "无效配置"
    
    print(analyze_config({"host": "localhost", "port": 8080}))
    # 服务器: localhost:8080
    
    print(analyze_config({"host": "0.0.0.0", "port": 443, "debug": True}))
    # 服务器: 0.0.0.0:443, 调试=开
    
    # ⚠️ 注意匹配顺序!上面的例子有个bug:
    # {"host": host, "port": port} 会先匹配,即使有debug键也会进入第一个case
    # 应该把更具体的模式放前面
    
    def analyze_config_fixed(config):
        match config:
            case {"host": host, "port": port, "debug": bool(debug)}:
                return f"服务器: {host}:{port}, 调试={'开' if debug else '关'}"
            case {"host": host, "port": int(port)}:
                return f"服务器: {host}:{port}"
            case {"database": db_config}:
                return f"数据库配置: {db_config}"
            case _:
                return "无效配置"
    

    3.3 匹配类实例

    # 匹配自定义类的实例
    class Point:
        def __init__(self, x, y):
            self.x = x
            self.y = y
    
    class Circle:
        def __init__(self, center, radius):
            self.center = center
            self.radius = radius
    
    class Rectangle:
        def __init__(self, top_left, bottom_right):
            self.top_left = top_left
            self.bottom_right = bottom_right
    
    def describe_shape(shape):
        match shape:
            case Point(x=0, y=0):
                return "原点"
            case Point(x=x, y=y):
                return f"点({x}, {y})"
            case Circle(center=Point(x=x, y=y), radius=r):
                return f"圆: 圆心({x}, {y}), 半径{r}"
            case Rectangle(top_left=Point(x=x1, y=y1), bottom_right=Point(x=x2, y=y2)):
                return f"矩形: ({x1},{y1}) 到 ({x2},{y2})"
            case _:
                return "未知形状"
    
    # 使用
    p1 = Point(0, 0)
    p2 = Point(3, 4)
    c = Circle(Point(1, 2), 5)
    r = Rectangle(Point(0, 0), Point(10, 10))
    
    print(describe_shape(p1))   # 原点
    print(describe_shape(p2))   # 点(3, 4)
    print(describe_shape(c))    # 圆: 圆心(1, 2), 半径5
    print(describe_shape(r))    # 矩形: (0,0) 到 (10,10)
    

    四、守卫条件(Guard)

    守卫条件让你在模式匹配的基础上添加额外的判断:

    # 使用 if 添加守卫条件
    def classify_value(x):
        match x:
            case int(n) if n > 0:
                return f"正整数: {n}"
            case int(n) if n < 0:
                return f"负整数: {n}"
            case int(n):        # n == 0
                return "零"
            case float(f) if f > 0:
                return f"正浮点数: {f}"
            case float(f) if f < 0:
                return f"负浮点数: {f}"
            case float(f):
                return "浮点数零"
            case str(s) if len(s) > 10:
                return f"长字符串({len(s)}字符): {s[:10]}..."
            case str(s):
                return f"短字符串: {s}"
            case _:
                return "其他类型"
    
    print(classify_value(42))           # 正整数: 42
    print(classify_value(-3.14))        # 负浮点数: -3.14
    print(classify_value("Hello"))      # 短字符串: Hello
    print(classify_value("Hello World! This is Python"))  # 长字符串(28字符)
    
    # 结合守卫和OR模式
    def check_age(age):
        match age:
            case int(n) if n < 0 | n > 150:
                return "无效年龄"
            case int(n) if n < 18:
                return "未成年人"
            case int(n) if n < 65:
                return "成年人"
            case int(n):
                return "老年人"
            case _:
                return "非数字输入"
    

    五、match-case vs if-elif-else

    5.1 什么时候用match-case

    # ✅ 适合match-case:基于值的多分支选择
    def get_day_type(day):
        match day.lower():
            case "monday" | "tuesday" | "wednesday" | "thursday" | "friday":
                return "工作日"
            case "saturday" | "sunday":
                return "周末"
            case _:
                return "未知"
    
    # ✅ 适合match-case:解构复杂数据结构
    def process_api_response(response):
        match response:
            case {"status": "ok", "data": data}:
                return handle_data(data)
            case {"status": "error", "message": msg}:
                return f"错误: {msg}"
            case {"status": "error", "code": int(code)} if code >= 500:
                return f"服务器错误([code])"
            case {"status": "error", "code": int(code)}:
                return f"客户端错误([code])"
            case _:
                return "未知响应格式"
    
    # ❌ 不适合match-case:需要复杂比较逻辑
    # 这种情况下if-elif-else更合适
    def analyze_score(score):
        # if-elif-else更合适
        if score >= 90:
            return "优秀"
        elif score >= 80:
            return "良好"
        elif score >= 70:
            return "中等"
        else:
            return "需要提升"
    

    5.2 两者的混合使用

    # match-case 和 if-elif-else 可以混合
    def smart_classifier(obj):
        # 先用match-case按类型分大类
        match obj:
            case int(n):
                # 再用if-elif按范围细分
                if n < 0:
                    return "负整数"
                elif n == 0:
                    return "零"
                elif n < 10:
                    return "小正整数"
                else:
                    return "大正整数"
            
            case str(s):
                if len(s) == 0:
                    return "空字符串"
                elif len(s) < 10:
                    return "短字符串"
                else:
                    return "长字符串"
            
            case list(items):
                if len(items) == 0:
                    return "空列表"
                elif all(isinstance(i, int) for i in items):
                    return "整数列表"
                else:
                    return "混合列表"
            
            case _:
                return f"不支持的类型: {type(obj).__name__}"
    

    六、实战案例

    6.1 JSON数据验证与解析

    def parse_user_data(data):
        """解析并验证用户数据"""
        match data:
            # 完整数据
            case {
                "name": str(name),
                "age": int(age),
                "email": str(email),
                **extra      # **extra 收集额外字段
            } if 0 < age < 150 and "@" in email:
                result = {
                    "name": name,
                    "age": age,
                    "email": email,
                    "valid": True,
                }
                if extra:
                    result["extra_fields"] = list(extra.keys())
                return result
            
            # 缺少email但有name和age
            case {"name": str(name), "age": int(age)} if 0 < age < 150:
                return {
                    "name": name,
                    "age": age,
                    "valid": True,
                    "warnings": ["缺少邮箱地址"],
                }
            
            # 只有name
            case {"name": str(name)}:
                return {
                    "name": name,
                    "valid": False,
                    "errors": ["缺少年龄和邮箱"],
                }
            
            # 空数据或格式不对
            case dict():
                return {"valid": False, "errors": ["数据格式不正确"]}
            
            case _:
                return {"valid": False, "errors": ["输入不是字典类型"]}
    
    # 测试
    test_cases = [
        {"name": "张三", "age": 25, "email": "zhangsan@example.com", "city": "北京"},
        {"name": "李四", "age": 30},
        {"name": "王五"},
        {"invalid": "data"},
        "not a dict",
    ]
    
    for data in test_cases:
        result = parse_user_data(data)
        print(f"n输入: {data}")
        print(f"输出: {result}")
    

    6.2 简易计算器

    def calculator():
        """命令行计算器,展示match-case的模式匹配能力"""
        print("简易计算器(输入 'quit' 退出)")
        print("支持格式:<数字> <操作符> <数字>")
        print("示例:10 + 20, 3.14 * 2, 100 / 4")
        
        while True:
            user_input = input("n> ").strip()
            
            if not user_input:
                continue
            
            match user_input.split():
                case ["quit" | "exit" | "q"]:
                    print("再见!")
                    break
                
                case ["help" | "h" | "?"]:
                    print("操作符: + (加), - (减), * (乘), / (除), ** (幂), % (取模)")
                    print("输入 'quit' 退出, 'clear' 清零")
                
                case ["clear" | "c"]:
                    print("计算器已重置")
                
                case [left, op, right]:
                    try:
                        a, b = float(left), float(right)
                        match op:
                            case "+":
                                result = a + b
                            case "-":
                                result = a - b
                            case "*" | "×" | "x":
                                result = a * b
                            case "/" | "÷":
                                if b == 0:
                                    print("❌ 除数不能为零!")
                                    continue
                                result = a / b
                            case "**" | "^":
                                result = a ** b
                            case "%":
                                result = a % b
                            case _:
                                print(f"❌ 未知操作符: {op}")
                                continue
                        print(f"  {a} {op} {b} = {result}")
                    except ValueError:
                        print("❌ 请输入有效的数字")
                
                case _:
                    print("❌ 格式错误,请使用: <数字> <操作符> <数字>")
    
    # 运行计算器(取消注释使用)
    # calculator()
    

    6.3 抽象语法树处理器

    # 用match-case处理简单的表达式树
    class Expr:
        pass
    
    class Number(Expr):
        def __init__(self, value):
            self.value = value
    
    class BinOp(Expr):
        def __init__(self, left, op, right):
            self.left = left
            self.op = op
            self.right = right
    
    class UnaryOp(Expr):
        def __init__(self, op, operand):
            self.op = op
            self.operand = operand
    
    def evaluate(expr):
        """递归计算表达式树的值"""
        match expr:
            case Number(value=n):
                return n
            
            case BinOp(left=l, op="+", right=r):
                return evaluate(l) + evaluate(r)
            
            case BinOp(left=l, op="-", right=r):
                return evaluate(l) - evaluate(r)
            
            case BinOp(left=l, op="*", right=r):
                return evaluate(l) * evaluate(r)
            
            case BinOp(left=l, op="/", right=r):
                divisor = evaluate(r)
                if divisor == 0:
                    raise ZeroDivisionError("除数不能为零")
                return evaluate(l) / divisor
            
            case UnaryOp(op="-", operand=opd):
                return -evaluate(opd)
            
            case UnaryOp(op="+", operand=opd):
                return evaluate(opd)
            
            case _:
                raise ValueError(f"未知表达式: {expr}")
    
    # 构建表达式: (-5 + 3) * 2
    expr = BinOp(
        BinOp(UnaryOp("-", Number(5)), "+", Number(3)),
        "*",
        Number(2)
    )
    print(f"(-5 + 3) * 2 = {evaluate(expr)}")    # -4
    

    七、本章小结

    本文我们学习了Python 3.10的match-case模式匹配语句:

    基本语法:match subject: case pattern: ... case _: ...,_是通配符。

    OR模式:case 1 | 2 | 3: 匹配多个值。

    变量绑定:case ["add", x, y]: 在匹配时提取值到变量。

    结构化匹配(核心特性):

    • 序列:[first, *rest]、[first, *middle, last]
    • 映射:{"key": value_pattern, **rest}
    • 类实例:Point(x=x, y=y)

    守卫条件:case pattern if condition: 在模式匹配基础上加条件。

    选型建议:match-case适合值匹配和结构解构,if-elif-else适合范围比较。两者可以混合使用。

    match-case是Python 3.10最重大的新特性。掌握了它,你处理复杂分支逻辑的能力将上升一个台阶。⌨️ 下一篇文章,我们将进入循环的世界——从while循环开始!

    本站声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系bd@zhengruan.com
    作者最新文章
    编程开发 Python
    相关文章 更多
    python删除一个列表里的重复元素的方法与代码示例
    python删除一个列表里的重复元素的方法与代码示例

    学习如何使用Python高效删除列表中的重复元素。本文提供5种常见方法的代码示例,涵盖保持顺序与不保持顺序的场景,适合初学者和进阶开发者参考。

    Python写接口的步骤及完整代码示例
    Python写接口的步骤及完整代码示例

    详细讲解使用Python编写Web接口的核心步骤与完整代码示例,涵盖环境准备、路由定义、数据校验、服务启动及调试测试方法。

    codex怎么读取word文档及docx文件操作教程
    codex怎么读取word文档及docx文件操作教程

    介绍如何利用编程工具读取和解析Word文档(docx格式),涵盖基础文本提取代码示例、结构化数据处理逻辑,以及处理复杂排版时的技术局限与替代方案。

    怎么在Python中调用C语言代码提升性能
    怎么在Python中调用C语言代码提升性能

    详细讲解在Python中调用C语言代码提升性能的完整实践指南,包含原理分析、编译步骤、ctypes与CFFI具体实现、性能对比及常见陷阱。

    Python与C语言的性能差异及底层原理
    Python与C语言的性能差异及底层原理

    深入解析Python与C语言在执行效率上的数量级差异,从编译机制、变量内存布局、动态类型推断到GIL锁,系统阐明底层核心原理。

    Python和C语言哪个更适合编程入门
    Python和C语言哪个更适合编程入门

    客观对比Python与C语言在心智负担、底层机制与学习反馈上的核心差异,提供清晰有据的选择标准与切实的入门学习路径。

    selenium上传文件教程本地文件路径设置方法
    selenium上传文件教程本地文件路径设置方法

    深入解析Selenium处理文件上传的技术细节,涵盖标准HTML控件的路径直接注入法与非标准控件的系统级模拟方案,提供Windows与Linux环境下的路径设置最佳实践及常见异常排查。

    大数据开发语言选型:Java对比Scala与Python的优缺点及适用场景
    大数据开发语言选型:Java对比Scala与Python的优缺点及适用场景

    针对大数据工程场景,系统对比Java、Scala与Python在执行性能、生态结合、开发效率和维护成本上的核心差异,给出清晰的架构选型依据与落地方案。

    langgraph python guide中文入门教程详解
    langgraph python guide中文入门教程详解

    本篇LangGraph Python中文入门教程详解,系统梳理StateGraph状态机定义、节点编写、边与条件路由、检查点持久化(MemorySaver)等核心机制,提供从环境安装到完整循环智能体构建的代码示例与实操指导。

    Windows 安装 Python:从官方入口到虚拟环境的可复现实践
    Windows 安装 Python:从官方入口到虚拟环境的可复现实践

    面向后端开发者,基于 Python 官方文档说明如何在 Windows 上安装 Python、创建 venv 虚拟环境及使用 pip 管理依赖。包含可复制命令、验证方法及工具选择边界,避免常见配置误区。

    查看更多
    精品专题 更多
    装机必备
    装机必备

    正软商城装机必备专区,精选办公、浏览器、安全防护、影音播放、压缩解压、设计创作和系统工具等电脑常用正版软件,帮助用户快速完成新电脑软件配置。

    Windows
    Windows

    正软商城Windows软件专区,汇集适用于Windows电脑的办公、设计、安全防护、影音播放、开发工具和系统优化软件,提供软件介绍、系统要求、正版授权及购买下载服务。

    PDF教程
    PDF教程

    正软商城PDF教程频道提供PDF编辑、转换、合并、拆分、压缩及格式处理方法,同时介绍常用PDF软件和工具的使用技巧。

    Mac软件 更多
    汽水音乐
    汽水音乐
    Android / iOS / Windows / macOS;按官网选择下载

    汽水音乐提供个性化推荐、场景电台及抖音音乐收藏衔接,适合发现歌曲和管理日常听歌内容。这里说明播放、一起听及多平台入口,并提醒区分曲目版权与会员权益。

    LibreOffice 桌面版
    LibreOffice 桌面版
    Windows / macOS / Linux 桌面版;按官网选择稳定分支和架构

    LibreOffice桌面版提供Writer、Calc、Impress等办公组件,可本地处理文档并交换Office格式。了解实际功能、商用许可、兼容性检查和企业支持的区别。

    Numbers macOS版
    Numbers macOS版
    macOS版;系统要求以 Mac App Store 当前页面为准

    Numbers macOS版用于预算、数据整理和可视化报告,支持公式、图表、数据透视表及iCloud协作。了解Excel文件交换、Mac安装条件和多端使用差异。

    WINDOWS 更多
    汽水音乐
    汽水音乐
    Android / iOS / Windows / macOS;按官网选择下载

    汽水音乐提供个性化推荐、场景电台及抖音音乐收藏衔接,适合发现歌曲和管理日常听歌内容。这里说明播放、一起听及多平台入口,并提醒区分曲目版权与会员权益。

    微信 Windows版
    微信 Windows版
    Windows版;按官网选择架构和适用系统,不固定历史小版本

    微信Windows版适合电脑聊天、会话查找和文件传送。本页说明登录与文件管理、电脑办公优势,以及大文件失败、版本差异和本地记录的核对方法。

    LibreOffice 桌面版
    LibreOffice 桌面版
    Windows / macOS / Linux 桌面版;按官网选择稳定分支和架构

    LibreOffice桌面版提供Writer、Calc、Impress等办公组件,可本地处理文档并交换Office格式。了解实际功能、商用许可、兼容性检查和企业支持的区别。