模式匹配

1. 基本语法

Python 3.10 引入了模式匹配语法 match-case,它比传统的 if-elif-else 结构更简洁、可读性更强。

1.1 基础用法

score = 'B'

match score:
    case 'A':
        print('优秀')
    case 'B':
        print('良好')
    case 'C':
        print('及格')
    case _:  # 通配符,匹配任何情况
        print('无效成绩')

1.2 与传统if语句对比

传统写法:

score = 'B'

if score == 'A':
    print('优秀')
elif score == 'B':
    print('良好')
elif score == 'C':
    print('及格')
else:
    print('无效成绩')

2. 进阶匹配模式

2.1 多值匹配

age = 15

match age:
    case x if x < 10:  # 带条件的匹配
        print(f'10岁以下: {x}')
    case 10:
        print('正好10岁')
    case 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18:  # 多值匹配
        print('11-18岁')
    case 19:
        print('19岁')
    case _:
        print('其他年龄')

2.2 列表匹配

args = ['gcc', 'hello.c', 'world.c']

match args:
    case ['gcc']:  # 仅gcc
        print('错误:缺少源文件')
    case ['gcc', file1, *files]:  # gcc + 至少一个文件
        print(f'编译: {file1}, 其他文件: {", ".join(files)}')
    case ['clean']:
        print('清理')
    case _:
        print('无效命令')

3. 高级特性

3.1 结构匹配

from dataclasses import dataclass

@dataclass
class Point:
    x: int
    y: int

point = Point(1, 2)

match point:
    case Point(x=0, y=0):
        print("原点")
    case Point(x=0):
        print(f"Y轴上: {point.y}")
    case Point(y=0):
        print(f"X轴上: {point.x}")
    case Point(x, y):
        print(f"普通点: ({x}, {y})")
    case _:
        print("不是点")

3.2 字典匹配

config = {'type': 'video', 'format': 'mp4', 'duration': 120}

match config:
    case {'type': 'video', 'format': 'mp4'}:
        print("MP4视频")
    case {'type': 'audio', 'format': 'mp3'}:
        print("MP3音频")
    case {'type': _, 'duration': t} if t > 60:
        print(f"长内容: {t}秒")
    case _:
        print("未知配置")

4. 最佳实践

  1. 顺序很重要:匹配是按顺序进行的,应该把最具体的模式放在前面
  2. 使用通配符case _ 应该放在最后,作为默认情况
  3. 类型检查:可以结合类型检查使用
    match value:
        case int():
            print("整数")
        case str():
            print("字符串")
        case _:
            print("其他类型")
  4. 性能考虑:对于简单的情况,if语句可能更高效

5. 实际应用示例

5.1 HTTP状态码处理

status_code = 404

match status_code:
    case 200:
        print("成功")
    case 301 | 302 | 303:
        print("重定向")
    case 400:
        print("错误请求")
    case 401 | 403:
        print("权限问题")
    case 404:
        print("未找到")
    case 500 | 502 | 503:
        print("服务器错误")
    case _:
        print(f"未知状态码: {status_code}")

5.2 命令解析器

command = input("请输入命令: ").split()

match command:
    case ['exit']:
        print("退出程序")
    case ['help']:
        print("显示帮助")
    case ['run', filename]:
        print(f"运行文件: {filename}")
    case ['search', *keywords]:
        print(f"搜索关键词: {' '.join(keywords)}")
    case _:
        print("无效命令")

总结

Python 的 match-case 语句提供了强大的模式匹配能力,可以:

  • 替代复杂的 if-elif-else
  • 解构复杂的数据结构
  • 提高代码可读性和可维护性
  • 处理多种情况时更简洁

在 Python 3.10+ 中,match-case 是处理多条件分支时的首选方案。