提问人:John Alley 提问时间:7/14/2012 最后编辑:llRub3NllJohn Alley 更新时间:5/17/2022 访问量:2305453
case/switch 语句的 Python 等效项是什么?[复制]
What is the Python equivalent for a case/switch statement? [duplicate]
问:
该语句是否有 Python 等价物?switch
答:
1068赞
Prashant Kumar
7/14/2012
#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.\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]()
如果你严重依赖失败,这就会开始分崩离析。
评论
44赞
flexxxit
2/27/2014
字典必须位于函数定义之后
17赞
Zaz
9/24/2015
关于跌倒,你不能用吗,还是我误会了?options.get(num, default)()
6赞
Prashant Kumar
9/24/2015
我想我的意思更多是标签执行一些代码,然后继续进入另一个标签的块。
8赞
Sanjay Manohar
7/26/2017
@IanMobbs 将代码放在引号中的常量字符串中几乎从来都不是“正确”的。1)您的编辑器不会检查代码的有效性。2)在编译时没有优化为字节码。3)你看不到语法突出显示。4) 如果您有多个引号,请挑剔 - 确实您的评论需要转义!如果你想要简洁,你可以改用一个,尽管我认为这被认为是非pythonic的。eval
lambda
110赞
333kenshin
9/6/2017
顺便说一句,2 是一个质数
270赞
Lennart Regebro
7/14/2012
#2
直接替换是 //。if
elif
else
但是,在许多情况下,在 Python 中有更好的方法可以做到这一点。请参阅“Python 中 switch 语句的替换?”。
评论
1赞
ArduinoBen
4/5/2022
这就是我最终选择的。我认为模式匹配不适用于字符串。
0赞
Derek Mahar
11/11/2023
模式匹配适用于字符串。
评论
match ... case
match
case