Python有类似于switch
语句的语法吗?
在 Python 3.10 中,他们引入了 模式匹配。
下面是摘自 Python 文档 的示例:
def http_error(status):
match status:
case 400:
return "Bad request"
case 404:
return "Not found"
case 418:
return "I'm a teapot"
# If an exact match is not confirmed, this last case will be used if provided
case _:
return "Something's wrong with the internet"
虽然官方文档不提供switch
,但我看到了一个使用字典的解决方案。
例如:
# define the function blocks
def zero():
print "You typed zero.\n"
def sqr():
print "n is a perfect square\n"
def even():
print "n is an even number\n"
def prime():
print "n is a prime number\n"
# map the inputs to the function blocks
options = {0 : zero,
1 : sqr,
4 : sqr,
9 : sqr,
2 : even,
3 : prime,
5 : prime,
7 : prime,
}
然后调用等效的 switch
块:
options[num]()
如果你严重依赖于穿透(fall through),这将开始崩溃。
options.get(num, default)()
,还是我有误解? - Zaz直接替换方案是使用if
/elif
/else
。
然而,在很多情况下,Python 中有更好的方法来实现相同的功能。请参考 "Python 中 switch 语句的替代方案?"。
match-case
结构的所有你可能想要了解的内容,包括如果你来自其他编程语言时会遇到的常见陷阱。当然,如果你还没有使用 Python 3.10.0,现有的答案仍然适用于2021年。 - fameman