TL;DR
As of Python 3.10.0 (alpha6 released https://docs.python.org/3.10/whatsnew/3.10.html2021 年 3 月 30 日),Python 有一个官方语法等效项,称为match https://docs.python.org/3.10/whatsnew/3.10.html#syntax-and-operations:%7E:text=A%20match%20statement%20takes%20an%20expression,as%20one%20or%20more%20case%20blocks..
基本语法是:
match value:
case condition:
action(s)
...
对于较旧的 Python 版本,如果您不想诉诸,则只有解决方法if
-elif
-else
。
看到这个优秀的社区帖子 https://stackoverflow.com/questions/60208/replacements-for-switch-statement-in-python一些的集合。
Example
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")
因此,从性能的角度来看,涉及解决方法的其他答案不再有效。
重要告示
如果来自支持的语言switch
and case
,您可能已经了解他们的行为。但对于 Python,有一些差异需要注意。
-
案件不会落空
语言具有以下特征是很常见的switch
-case
语句执行everycase 值匹配 - 从上到下。于是,就有了第三种说法——break
- 用于switch
-case
如果你不想失败的话可以构造:
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.");
}
在这个例子中,第一个two案件将被执行,因为第一个案件失败了。如果没有break
第二种情况下的语句,所有情况,包括默认情况,都将被执行。
在Python中,仅第一个匹配的情况正在被执行。你可以把它想象成每个案例都包含一个隐藏的break
陈述。
-
变量引用不能作为条件
base_color = "red"
chosen_color = "green"
match chosen_color:
case base_color:
print("Yes, it matches!")
这段代码实际上打印出颜色匹配!
作为 case 条件的裸变量引用将始终匹配。
无论如何,文字就像case "red": ...
and 合格的(即点)名称,例如case AllColors.red
按预期工作 - 无需害怕他们。
所有这一切都是如此,因为Python软件基金会并没有决定只是复制另一个无聊的控制流模型,而是实际实现一个成熟的控制流模型模式匹配器这不仅仅是一个switch
-case
陈述。有关这方面的更多信息可以在下一节中找到。
强大的模式匹配
match
- Match ain't case hooey
Specification and information provided in the Python Enhancement Proposals (PEP) nos. 634-636 https://www.python.org/dev/peps/pep-0634/
在Python中,match
实际上不仅仅是一个简单的开关 - 因此可能是这个名字。它具有特殊功能,例如深度占位符和通配符。
示例受到阅读文档的启发 - 因此您不必:
match point:
case (0, 0):
print("Origin")
case (0, y):
print("Our current Y position is", y, " now.")
您可以匹配任意嵌套数据结构,包括占位符。在上面的示例中,我们将一个元组与两个项目进行匹配,在第二种情况下,我们使用占位符y
在匹配时获得其值。
您还可以以非常相似的方式匹配类属性:
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.")
这也解释了为什么在 case 条件下无法匹配单个变量引用:您实际上并不匹配该变量的值,而是实际上引入了同名的占位符!
因此,如果您要打印chosen_color
像这样:
base_color = "red"
chosen_color = "green"
match chosen_color:
case base_color:
print("Our base color is", base_color)
它实际上会打印出来
我们的基色是绿色
因为base_color
现在是一个占位符,它被分配了我们的值chosen_color
.
这种高级模式匹配还有很多用例,其中一些有趣的例子在Python 文档 https://docs.python.org/3.10/whatsnew/3.10.html#pep-634-structural-pattern-matching.
Epilogue
Python 3.10 得到应有的采用还需要一段时间。 Python 3.10.0 将于 发布稳定版2021 年 10 月 4 日- 意味着它可能包含在 Ubuntu 22.04 及更高版本中。
如果您只是想自己玩玩并编写程序,将它们部署到您自己的服务器,或者如果您打算以打包形式而不是作为纯源代码文件分发您的作品,请在您的程序中尝试一下这个新功能 -这将是一个好处!
Addendum
尝试Python 3.10.0
对于 Windows 和 macOS 用户,这一页 https://www.python.org/downloads/release/python-3100a6/#content:%7E:text=Files具有官方安装程序下载。
On Debian https://en.wikipedia.org/wiki/Debian和 Ubuntu 一样,您可以使用非常流行的“DeadSnakes”项目 PPA:
sudo add-apt-repository ppa:deadsnakes/ppa
sudo apt update
sudo apt install python3.10
python3.10 --version
在不破坏系统的情况下尝试 Python 3.10.0
Docker https://en.wikipedia.org/wiki/Docker_(software)是在完全隔离的环境中使用 Python 3.10 的选项,无需任何复杂的设置步骤。
docker run -it python:3.10.0a6-alpine
就是这样。随着时间的推移,可能会发布新的 alpha 或 beta 版本。您将想要更换a6
with a then.