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]()
如果你严重依赖失败,这就会开始崩溃。
其他回答
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]()
如果你严重依赖失败,这就会开始崩溃。
直接替换为if/elif/else。
然而,在许多情况下,在Python中有更好的方法来实现它。参见“Python中switch语句的替换?”。
推荐文章
- Visual Studio Code:如何调试Python脚本的参数
- 使用元组/列表等等。从输入vs直接引用类型如list/tuple/etc
- 结合conda环境。Yml和PIP requirements.txt
- 将命名元组转换为字典
- 如何使x轴和y轴的刻度相等呢?
- Numpy在这里函数多个条件
- 在Python中,使用argparse只允许正整数
- 如何排序mongodb与pymongo
- 不可变与可变类型
- 列表是线程安全的吗?
- 操作系统。makdirs在我的路径上不理解“~”
- 如何在Django模板中获得我的网站的域名?
- 在django Forms中定义css类
- 如何在Python中scp ?
- Numpy Max vs amax vs maximum