Python 中 case/switch 语句的等效语句是什么?[重复]
- 2024-12-20 08:37:00
- admin 原创
- 119
问题描述:
Python 中是否有与该switch
语句等效的语句?
解决方案 1:
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 之前
尽管官方文档不愿提供switch
,但我看到了使用字典的解决方案。
例如:
# define the function blocks
def zero():
print "You typed zero.
"
def sqr():
print "n is a perfect square
"
def even():
print "n is an even number
"
def prime():
print "n is a prime number
"
# 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,那么这一切都会开始崩溃。
解决方案 2:
直接替换就是if
/ elif
/ else
。
然而,在很多情况下,Python 中有更好的方法来实现这一点。请参阅“Python中 switch 语句的替代品? ”。
相关推荐
热门文章
项目管理软件有哪些?
热门标签
云禅道AD