在 Python 中,match 关键字用于模式匹配,在 Python 3.10 中作为结构模式匹配的一部分引入,类似于其他语言中的 switch 语句,但功能更强大。
什么是 match 关键字?
从 Python 3.10 开始,match 语句引入了结构化模式匹配(Structural Pattern Matching)。它类似于其他语言中的 switch 语句,但功能更加强大和灵活。
使用 match 的基本示例
def handle(value):
match value:
case 1:
print("一")
case 2:
print("二")
case _:
print("其他")
它的行为类似于 C 或 JavaScript 中的 switch-case 语句,但支持更多的模式匹配能力。
传统方式:if–elif–else
在 Python 3.10 之前,最常见的写法是使用 if–elif 结构:
def handle(value):
if value == 1:
print("一")
elif value == 2:
print("二")
else:
print("其他")
这种方式依然常见,适合处理简单的分支逻辑。
使用 dict 实现函数分发
另一种更 Pythonic 的技巧是使用字典来映射数值到处理函数:
def handle_one():
print("一")
def handle_two():
print("二")
def handle_default():
print("默认")
handlers = {
1: handle_one,
2: handle_two
}
value = 2
handlers.get(value, handle_default)()
这种方式可以避免多层嵌套的 if–elif,让代码更清晰。
match 更高级的匹配用法
匹配元组
point = (0, 1)
match point:
case (0, 0):
print("原点")
case (0, y):
print(f"Y={y}")
case (x, 0):
print(f"X={x}")
case (x, y):
print(f"X={x}, Y={y}")
匹配类对象
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
p = Point(1, 2)
match p:
case Point(x=0, y=0):
print("原点")
case Point(x, y):
print(f"点在 ({x}, {y})")
使用通配符 _
下划线 _ 被用作通配符匹配任意内容,相当于 switch 的 default 分支:
match x:
case "a":
print("匹配到 a")
case _:
print("默认分支")
对比表格
| 方式 | 支持的 Python 版本 | 适用场景 | 是否支持复杂匹配 |
|---|---|---|---|
if–elif–else |
所有版本 | 简单逻辑 | 不支持 |
dict 分发 |
所有版本 | 函数路由 | 支持有限 |
match |
Python 3.10+ | 高级结构化匹配 | 支持 |
总结
match在 Python 3.10+ 提供了简洁且功能强大的模式匹配能力if–elif依旧是兼容性强且直观的选择dict分发适用于需要将值映射到函数执行的场景
- 当需要兼容老版本 Python 或逻辑简单时,使用
if–elif。 - 如果逻辑是基于数值跳转函数,可使用
dict分发。 - 在 Python 3.10+ 环境中需要更优雅的模式匹配时,推荐使用
match。
Python 人生苦短,我用Python
英文:Python Match vs Traditional If-Elif: A Modern Take on Switch Statements
本文一共 454 个汉字, 你数一下对不对.上一篇: TEMU 英国拼多多确实便宜
下一篇: 伦敦法国申根签证的几个坑: 申请一次签证半条命
扫描二维码,分享本文到微信朋友圈