文章目录
- 模式匹配 match语句(仅在 Python 3.10及以上版本 中可用)
- 基本语法
- 基本匹配操作
- 应用场景
模式匹配 match语句(仅在 Python 3.10及以上版本 中可用)
- Python 3.10 及以上版本中才引入了 match 语句
- 用于简化复杂的条件判断和数据解构;类似于其他语言中的 switch-case 语句,但功能更强大,支持 结构化模式匹配 (Structural Pattern Matching)
基本语法
# match subject:
# case pattern1:
# #当 subject 匹配 pattern1 时执行的代码
# case pattern2:
# #当 subject 匹配 pattern2 时执行的代码
# ...
# case _:
# # 当 subject 不匹配时任何前面的模式时执行的代码
基本匹配操作
- 匹配常量
可以匹配 单个值 :
x = 902
match x:
case 902:
print('Happy birthday!')
case _:
print('this is not my birthday')
也可以匹配 多个值 ,多个值之间用 | 分隔:
x = -2
match x:
case 0:
print('x等于0')
case 1|2|3|4:
print('x为正数')
case -1|-2|-3|-4:
print('x为负数')
case _:
print('shayebushi')
- 匹配变量
point = (0,0)
# point = (1,-1)
match point:
case (x,y):
print(f'Coordinates are ({x},{y})')
#如果 point 是一个包含两个元素的元组,会将元组的值分别赋给 x 和 y 变量上并打印坐标
- 匹配元组
# tuple = () # 输出: 空元组
tuple = (1,) # 输出: 单元素元组,元素为 1
# tuple = (1, 2) # 输出: 双元素元组,元素为 1,2
# tuple = (1, 2, 3, 4, 5) # 输出: 多个元素元组,前两个为 1 和 2,剩余 (3, 4,5)
match tuple:
case ():
print("空元组")
case (x,):
print(f"单元素元组,元素为 {x}")
case (x, y):
print(f"双元素元组,元素为 {x} 和 {y}")
case (x, y, *rest):
print(f"多个元素元组,前两个为 {x} 和 {y},剩余 {rest}")
- 匹配列表
假设用户输入一个命令,用 args = [‘gcc’,‘hello.c’] 存储,用 match 匹配来解析这个列表
args = ['gcc','hello.c','world.c']
# args = ['clean']
# args = ['gcc']
match args:
# 如果列表中仅有 'gcc' 字符串,没有指定文件名,报错:
case ['gcc']:
print('gcc: missing source file(s).')
# 出现gcc,且至少指定了一个文件:
# 列表第一个字符串是 'gcc',第二个字符串赋给变量 files,后面的所有任意个字符串绑定到 *files(表明至少指定一个文件)
case ['gcc',file1,*files]:
print('gcc compile:' + file1 + ',' + ','.join(files))
# 列表仅有 'clean'一个字符串:
case ['clean']:
print('clean')
# 其他所有情况
case _:
print('invalid command.')
- 匹配字典
d = {'name':'echo','age':'24'}
match d:
case {"name": name, "age": age}:
print(f"用户 {name},年龄 {age}")
case {"error": code}:
print(f"错误码: {code}")
case _:
print("未知格式")
- 条件匹配
可以在 case 语句中使用 if 来添加额外的条件(守卫条件),只有当模式匹配且守卫条件为 True 时,才会执行相应的代码块
# value = 0
value = 10
# value = -10
match value:
case x if x < 0:
print("负数")
case x if x == 0:
print("零")
case x if x > 0:
print("正数")
应用场景
- 处理复杂的条件分支:多个复杂的条件需要判断时
- 解析数据结构:解析JSON数据、处理复杂的配置文件
- 状态机实现:根据不同状态和事件进行状态转换的判断