














⚠️ match-case 是 Python 3.10 及以上版本才支持的语法,类似其他语言的
switch-case,但功能更强,叫模式匹配。
score = 88
match True:
case _ if score >= 85:
print("优秀")
case _ if 75 <= score < 85:
print("良好")
case _ if 60 <= score < 75:
print("中等")
case _:
print("差")
输出:
优秀
match True::匹配目标写True,后面case用守卫条件 if 判断分数,用来替代多分支 if。case _:_ 是通配符,匹配任意值,相当于 if-else 的最后 else。case _ if 条件: 这个if叫守卫(guard),只有条件成立才匹配成功。这种写法只是模拟 if 多分支,match 真正强项不是单纯数值判断,而是解构匹配。
status = 2
match status:
case 0:
print("待处理")
case 1:
print("处理中")
case 2:
print("已完成")
case _:
print("未知状态")
输出:
已完成
match status::拿变量status去依次匹配下面case后的常量。case _ 必须放最后,兜底所有其它值。point = (10, 20)
match point:
case (0, 0):
print("原点")
case (x, 0):
print(f"在x轴上,x={x}")
case (0, y):
print(f"在y轴上,y={y}")
case (x, y):
print(f"普通点,坐标:x={x},y={y}")
输出:
普通点,坐标:x=10,y=20
if做不到的。if:侧重布尔条件判断;match:侧重结构匹配 + 值匹配 + 变量绑定,适合匹配元组、列表、对象结构。if elif更简单;匹配数据结构时,match优势巨大。此内容由惯性聚合(RSS阅读器)自动聚合整理,仅供阅读参考。 原文来自 — 版权归原作者所有。