Python 3.10引入match语句实现模式匹配,支持字面量、变量、结构、类实例等多种模式,可结合守卫条件和OR模式进行灵活匹配,按顺序执行首个匹配分支,提升处理结构化数据的代码可读性。

Python 3.10 引入了 match 语句,这是 Python 首次原生支持模式匹配(Pattern Matching),类似于其他语言中的“switch”语句,但功能更强大。它不仅支持简单的值比较,还能解构数据结构、绑定变量、进行类型检查等。
match 语的基本形式如下:
match subject:
case pattern1:
action1
case pattern2:
action2
...
case _:
default_action
其中:
match 支持多种模式,可以灵活组合使用。
立即学习“Python免费学习笔记(深入)”;
1. 字面量模式(Literal Patterns)
匹配具体的值,如数字、字符串、True、False、None 等。
match status:
case 400:
print("Bad request")
case 404:
print("Not found")
case 500:
print("Server error")
case _:
print("Unknown status")
2. 变量模式与通配符
单独一个名称会捕获该值并绑定到变量;_ 不绑定任何变量。
match point:
case (0, 0):
print("Origin")
case (0, y):
print(f"Y-axis at y={y}")
case (x, 0):
print(f"X-axis at x={x}")
case (x, y):
print(f"Point at ({x}, {y})")
注意:只有 _ 不会被当作变量绑定,其他字母都会创建或覆盖变量。
3. 结构模式(Sequence、Mapping)
可匹配列表、元组、字典等结构。
# 匹配元组结构
match command.split():
case ["quit"]:
print("Goodbye!")
case ["move", direction]:
print(f"Moving {direction}")
case ["attack", target]:
print(f"Attacking {target}")
<h1>匹配列表(支持可变长度)</h1><p>match items:
case [first, *rest]:
print(f"First: {first}, Rest: {rest}")
case []:
print("Empty list")</p><h1>匹配字典</h1><p>match user:
case {"name": name, "age": age}:
print(f"User: {name}, Age: {age}")</p>4. 类实例模式
可用于匹配类的实例,并提取其属性。
class Point:
__match_args__ = ('x', 'y')
def __init__(self, x, y):
self.x = x
self.y = y
<p>match point:
case Point(0, 0):
print("Origin")
case Point(x, y) if x == y:
print(f"Lies on line y=x at ({x}, {y})")
case Point(x, y):
print(f"Point at ({x}, {y})")</p>注意:__match_args__ 定义了解构顺序,方便位置参数匹配。
5. 条件守卫(Guard)
在 case 后使用 if 添加额外条件。
match point:
case (x, y) if x > 0 and y > 0:
print("First quadrant")
case (x, y) if x < 0 and y > 0:
print("Second quadrant")
case _:
print("Other quadrants")
守卫条件必须为真才算匹配成功。
6. 多重模式(OR 模式)
使用 | 表示多个模式任一匹配即可。
match value:
case int() | float() if value > 0:
print("Positive number")
case str() | list() if len(value) == 0:
print("Empty sequence")
注意:带守卫的 OR 模式中,守卫适用于整个组合。
使用 match 语句时需注意以下几点:
基本上就这些。match 语句让 Python 在处理结构化数据和状态分发时更加简洁直观,合理使用能显著提升代码可读性。虽然功能强大,但也别过度设计模式,保持代码清晰最重要。
以上就是Python3.10match语句语法详解_match语句Python3.10语法完整说明的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号