Python中的case/switch语句等价于什么?

823

Python有类似于switch语句的语法吗?


44
自 Python 3.10 起,您可以使用 Python 的“match ... case”语法:PEP 636 - iacob
36
Python 3.10.0 提供了一个官方的语法等价替代,使得之前提交的答案不再是最优解!在 这篇 Stack Overflow 帖子中,我试图涵盖关于 match-case 结构的所有你可能想要了解的内容,包括如果你来自其他编程语言时会遇到的常见陷阱。当然,如果你还没有使用 Python 3.10.0,现有的答案仍然适用于2021年。 - fameman
3
我本想在这篇帖子下写回答,但不幸的是它已经不能再接受任何回答了。然而,有超过一百万的浏览量,我认为这个问题至少需要一个更现代的答案指引——尤其是当3.10.0版本稳定后,Python初学者遇到这篇帖子时。 - fameman
2个回答

1072

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]()

如果你严重依赖于穿透(fall through),这将开始崩溃。


44
函数定义后必须放置字典。 - flexxxit
17
关于 fall-through,你能否使用 options.get(num, default)(),还是我有误解? - Zaz
6
我认为我更多是指标签执行一些代码,然后继续进入另一个标签的块的情况。 - Prashant Kumar
8
@IanMobbs,几乎从不适合将代码放在带引号的常量字符串中,然后进行eval。1)编辑器不会检查代码的有效性。2)编译时不会将其优化为字节码。3)你看不到语法高亮。4)如果有多个引号,会很繁琐,事实上你的注释需要转义!如果想简洁,可以使用lambda,但我认为这被认为是非Python风格的。 - Sanjay Manohar
110
顺带一提,2是一个质数。 - 333kenshin
显示剩余10条评论

272

1
这就是我最终采用的方案。我认为模式匹配在字符串上不起作用。 - ArduinoBen
模式匹配可以用于字符串。 - undefined

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接