case/switch 语句的 Python 等效项是什么?[复制]

What is the Python equivalent for a case/switch statement? [duplicate]

提问人:John Alley 提问时间:7/14/2012 最后编辑:llRub3NllJohn Alley 更新时间:5/17/2022 访问量:2305453

问:

该语句是否有 Python 等价物?switch

python switch-statement 匹配 案例

评论

44赞 iacob 3/27/2021
从 Python 3.10 开始,您可以使用 Python 的语法:PEP 636match ... case
35赞 fameman 4/3/2021
Python 3.10.0 提供了官方语法等价物,使提交的答案不再是最佳解决方案!这篇 SO 文章中,我试图涵盖您可能想知道的有关 - 结构的所有信息,包括来自其他语言的常见陷阱。当然,如果您还没有使用 Python 3.10.0,现有的答案适用,并且在 2021 年仍然有效。matchcase
3赞 fameman 4/3/2021
我会在这篇文章的答案中写下这个,但不幸的是,它不允许更多的答案。但是有超过一百万的浏览量,我认为这个问题至少需要重定向到一个更现代的答案 - 特别是当 3.10.0 变得稳定并且 Python 初学者遇到这篇文章时。

答:

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的。evallambda
110赞 333kenshin 9/6/2017
顺便说一句,2 是一个质数
270赞 Lennart Regebro 7/14/2012 #2

直接替换是 //。ifelifelse

但是,在许多情况下,在 Python 中有更好的方法可以做到这一点。请参阅“Python 中 switch 语句的替换?”

评论

1赞 ArduinoBen 4/5/2022
这就是我最终选择的。我认为模式匹配不适用于字符串。
0赞 Derek Mahar 11/11/2023
模式匹配适用于字符串。