在Python中,与switch/case等效的语法是什么? [英] What is the syntactical equivalent to switch/case in Python?

查看:114
本文介绍了在Python中,与switch/case等效的语法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

诸如C/C ++,C#,Java,JavaScript和Pascal等编程语言(参考)具有 switch case 语句的组合(有时也称为 select inspect ),您可以根据几种条件检查一个值以执行某些操作.

Programming languages like C/C++, C#, Java, JavaScript and Pascal (Reference) have a combination of switch and case statements (sometimes also called select or inspect) which allow you to check one value against several conditions to perform certain actions.

my_value = 10;
switch(my_value) {
    case 10:
        print("The number is ten");
    case 2*10:
        print("The number is the double of ten");
    case 100:
        print("The number is one hundred");
    default:
        print("The number is none of 10, 2*10 or 100");
}

伪代码,用于描述 switch - case 构造的特殊语法.

Pseudo-Code to depict the special syntax of the switch-case construct.

了解类似字典查找之类的功能等效项时,是否有纯粹的语法等效项上面的编程结构?

Being aware of functional equivalents like dictionary-lookups, is there a purely syntactical equivalent to the above programming construct?

推荐答案

TL; DR

Python 3.10.0 (alpha6 发布(2021年3月30日) ,Python具有称为 匹配 .

TL;DR

As of Python 3.10.0 (alpha6 released March 30, 2021) , Python has an official syntactial equivalent called match.

基本语法是:

match value:
    case condition:
        action(s)
    ...


对于较旧的Python版本,只有在不想使用 if - elif - else 的情况下,才有解决方法./>请参阅这篇出色的社区帖子,以获取一些相关文章.


For older Python versions, there are only workarounds if you don't want to resort to if-elif-else.
See this excellent community post for a collection of some.

my_value = 10
match my_value:
    case 10:
        print("The number is ten")
    case 2*10:
        print("The number is the double of ten")
    case 100:
        print("The number is one hundred")
    case _:
        # this is the default handler if none
        # of the above cases match.
        print("The number is none of 10, 2*10 or 100")

因此,从性能角度来看,涉及变通办法的其他答案也不再有效.

Therefore, other answers involving workarounds aren't valid anymore - also from a performance point of view.

如果来自支持 switch case 的语言,则可能您已经知道它们的行为.使用Python时,需要注意一些差异.

If coming from languages which support switch and case , it's likely that you already know about their behavior. With Python, there are some differences to note though.

  • 案件没有落空
    带有 switch - case 语句的语言通常在值匹配的情况下执行个语句-从上到下.因此,如果您不想跌破第三条语句,请在 switch - case 构造中使用第三条语句- break /p>

  • cases don't fall through
    it's common that languages with switch-case statements execute every case the value matches - from top to bottom. Hence, there is a third statement - break - to be used in switch-case constructs if you don't want to fall through:

value = 10
switch (value) {
    case 10:
        print("Value is ten");
    case 2*5:
        print("Value is the double of five");
        break;
    case 20/2:
        print("Value is the half of twenty");
    default:
        print("This is just the default action.");
}

在此示例中,将执行前两个案例,因为第一个案例失败了.如果第二种情况下没有 break 语句,则所有情况(包括默认情况)都将执行.

In this example, the first two cases would be executed because the first case falls through. If there was no break statement inside the second case, all cases, including the default one, would be executed.

在Python中,仅执行第一个匹配的情况.您可以将其想像成每种情况都包含一个隐藏的 break 语句.

In Python, only the first matching case is being executed. You can think of it like every case would contain a hidden break statement.

变量引用不能作为条件

base_color = "red"
chosen_color = "green"
match chosen_color:
    case base_color:
        print("Yes, it matches!")

此代码实际上会打印出颜色匹配的东西!

this code does actually print that the colors match!

裸露的变量引用,因为大小写条件将始终匹配.

无论如何,像 case AllColors.red 这样的文字都可以正常工作,例如 case"red":... qualified (即点缀)名称.像预期的那样-不必害怕它们.

Regardless, literals like case "red": ... and qualified (i.e. dotted) names like case AllColors.red work like expected - no need to be scared of them.

所有情况都是如此,因为Python Software Foundation并没有决定只复制另一个无聊的控制流模型,而是实际上实现了一个成熟的 pattern matcher ,它不仅仅是一个 switch - case 语句.有关更多信息,请参见下一部分.

All of this is the case, because the Python Software Foundation did not decide to just copy another boring control flow model, but to actually implement a fully-fledged pattern matcher which is more than just a switch-case statement. More on this can be found in the next section.

匹配- M 匹配 a 中的 t c > h ooey

match - Match ain't case hooey

Python增强建议(PEP)号中提供的规范和信息.634-636

在Python中, match 实际上不仅仅是一个简单的开关-因此可能就是名称.它具有特殊功能,如深占位符和通配符.

In Python, match is actually much more than a simple switch - therefore probably the name. It features special functionality like deep placeholders and wildcards.

示例是受文档启发而产生的-因此您不必:

match point:
    case (0, 0):
        print("Origin")
    case (0, y):
        print("Our current Y position is", y, " now.")

您可以匹配任意嵌套的数据结构,包括占位符.在上面的示例中,我们将一个元组与两个项目进行匹配,在第二种情况下,我们使用一个占位符 y ,该占位符在匹配时得到其值.

You can match arbitrary nested data structures, including placeholders. In the above example, we are matching a tuple with two items where in the second case, we use a placeholder y that gets its value assigned upon matching.

您也可以以非常相似的方式匹配类属性:

You can also match class attributes, in a very similar fashion:

class Point:
    x: int
    y: int

def location(point):
    match point:
        case Point(x=0, y=0):
            print("Origin is the point's location.")
        case Point(x=0, y=y):
            print("The point lies on the y axis at a height of", y, "units.")

这也解释了为什么在某些情况下不能匹配单个变量引用的原因:您实际上没有与该变量的值匹配,而是实际上引入了一个同名的占位符!因此,如果您要像这样打印 chosen_color :

This also explains why you can't match single variable references in case conditions: you don't actually match against the value of that variable but actually introduce a placeholder of that same name! Therefore, if you were going to print chosen_color like this:

base_color = "red"
chosen_color = "green"
match chosen_color:
    case base_color:
        print("Our base color is", base_color)

它实际上会打印出来

我们的基础颜色是绿色

Our base color is green

因为 base_color 现在是一个占位符,已为其分配了 chosen_color 的值.

because the base_color is now a placeholder which gets assigned the value of our chosen_color.

此高级模式匹配还有很多用例,在

There are a lot more use cases for this advanced pattern matching, an interesting couple of them mentioned in the Python Docs.

它需要时间,直到Python 3.10得到应有的采用.Python 3.10.0设置为将于2021年10月4日稳定发布.-这意味着它可能会包含在Ubuntu 22.04及更高版本中.

It will take its time until Python 3.10 gets its deserved adoption. Python 3.10.0 is set to be released stable on October 4, 2021 - meaning it might be included in Ubuntu 22.04 and up.

如果您只是想自己玩耍并编写程序,将它们部署到自己的服务器上,或者打算以打包形式而不是纯源代码文件的形式分发您的创作,请尝试使用此新功能您的程序-这将是一个好处!

If you just want to play around and write programs for yourself, deploy them to your own server, or if you intend to distribute your creations in packaged form and not as plain source code files, give this new feature already a try in your programs - it's going to be a benefit!

对于Windows和MacOS用户,此页面具有官方安装程序下载的功能.

For Windows and MacOS users, this page features the official installer downloads.

在Debian和Ubuntu上,您可以使用非常流行的"DeadSnakes"项目PPA:

On Debian and Ubuntu, you can use the very popular "DeadSnakes"-project PPA:

sudo add-apt-repository ppa:deadsnakes/ppa
sudo apt update
sudo apt install python3.10
python3.10 --version

尝试使用Python 3.10.0而不破坏系统

Docker 是使用Python 3.10的选项,而无需任何复杂的设置步骤,并且一个完全孤立的环境.

Trying Python 3.10.0 without destroying your system

Docker is an option for using Python 3.10 without any complicated setup steps and in a completely isolated environment.

docker run -it python:3.10.0a6-alpine

就是这样.随着时间的流逝,可能会发布新的Alpha或Beta版本.您将要用a6 然后7E:text = Simple%20Tags"rel =" noreferrer>不同版本.

And that's it. As the time passes by, new alpha or beta versions might be released. You will want to replace the a6 with a different version then.

这篇关于在Python中,与switch/case等效的语法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆