Python中是否有等效的switch语句?
当前回答
直接替换为if/elif/else。
然而,在许多情况下,在Python中有更好的方法来实现它。参见“Python中switch语句的替换?”。
其他回答
直接替换为if/elif/else。
然而,在许多情况下,在Python中有更好的方法来实现它。参见“Python中switch语句的替换?”。
Python 3.10及以上版本
在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"
Python 3.10之前
虽然官方文档很乐意不提供切换,但我已经看到了使用字典的解决方案。
例如:
# 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,
}
然后调用等效开关块:
options[num]()
如果你严重依赖失败,这就会开始崩溃。
推荐文章
- 证书验证失败:无法获得本地颁发者证书
- 当使用pip3安装包时,“Python中的ssl模块不可用”
- 无法切换Python与pyenv
- Python if not == vs if !=
- 如何从scikit-learn决策树中提取决策规则?
- 为什么在Mac OS X v10.9 (Mavericks)的终端中apt-get功能不起作用?
- 将旋转的xtick标签与各自的xtick对齐
- 为什么元组可以包含可变项?
- 如何合并字典的字典?
- 如何创建类属性?
- 不区分大小写的“in”
- 在Python中获取迭代器中的元素个数
- 解析日期字符串并更改格式
- 使用try和。Python中的if
- 如何在Python中获得所有直接子目录