Python 3.10 及以上版本
在 Python 3.10 中,他们引入了模式匹配.
示例来自Python 文档 https://docs.python.org/3.10/whatsnew/3.10.html#pep-634-structural-pattern-matching:
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"
Python 3.10 之前
虽然官方文档 http://docs.python.org/tutorial/controlflow.html很高兴不提供switch
,我见过一个使用字典的解决方案 http://bytebaker.com/2008/11/03/switch-case-statement-in-python/.
例如:
# 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]()
如果你严重依赖失败,这种情况就会开始崩溃。