Python 中没有 switch 语句,用什么替代?
Python 3.10+ 有 match-case 结构模式匹配;更早版本用 if-elif-else、字典映射(值可以是函数)替代 switch。本文对比各种方案。
Python 3.10+ 直接用 match-case(结构模式匹配,比 switch 更强大);老版本用 if-elif-else 或字典映射**(键→值/函数)替代。**
方案一:match-case(Python 3.10+,推荐)
def handle(status):
match status:
case 200:
return "成功"
case 404:
return "未找到"
case 500 | 502 | 503: # 多值匹配
return "服务器错误"
case _: # 默认分支
return "未知状态"
match 还能解构数据:case {"code": 200, "data": d}: 直接提取字段。
方案二:if-elif-else(最通用)
def handle(status):
if status == 200:
return "成功"
elif status == 404:
return "未找到"
else:
return "未知状态"
方案三:字典映射(分支多且固定时最优雅)
def handle(status):
messages = {
200: "成功",
404: "未找到",
500: "服务器错误",
}
return messages.get(status, "未知状态")
值还可以是函数,实现"分发":
handlers = {
'create': create_handler,
'delete': delete_handler,
}
handlers[action]() # 按 key 调用对应函数
常见问题(FAQ)
Q:match 和 if-elif 性能差别大吗?
A:分支少时没差别;分支很多时字典是 O(1) 查找,if-elif 是 O(n) 逐个比较。
Q:match 会"贯穿"(fall-through)吗?
A:不会。Python 的 match 匹配一个分支后自动结束,不需要 break。
Q:字典映射能处理区间条件吗(如分数段)?
A:不能。区间判断用 if-elif 或 bisect 模块。