Python 中的 match-case 模式匹配
Python 3.10 引入的 match-case(结构化模式匹配)语法如何使用?请举例说明。
回答
屠龙少年
match-case 是类似 switch 的语法,但功能更强大,支持模式解构。
def process(data):
match data:
case 0:
print('Zero')
case 1 | 2:
print('Small number')
case int(n) if n > 100:
print(f'Big integer: {n}')
case [x, y]:
print(f'List of two: {x}, {y}')
case {'name': name, 'age': age}:
print(f'{name} is {age} years old')
case _:
print('Something else')
process(0) # Zero
process(1) # Small number
process(200) # Big integer: 200
process([3, 4]) # List of two: 3, 4
process({'name': 'Alice', 'age': 30}) # Alice is 30 years old
模式类型:字面量、通配符 _、OR 模式 |、守卫 if、序列模式、映射模式、类模式、捕获模式。