if 语句与 Python 中的 match/case 语句有何不同?

MOO*_*OON 14 python if-statement match

问题要求使用 Python 中的 aswitch/casematch/case等效项。看来从Python 3.10开始我们现在可以使用match/case语句了。除了语法差异之外,我无法看到和理解match/case和陈述之间的区别!if, elif

是否存在根本差异导致它们具有不同的性能?或者以某种方式使用match/case我们可以更好地控制流量?但如何?match/case有没有比仅仅陈述更好的例子if

Wil*_*lva 13

PEP 622深入解释了新的 match-case 语句的工作原理其背后的基本原理,并提供了它们比 if 语句更好的示例

在我看来,if 语句的最大改进是它们允许结构模式匹配,正如 PEP 的名字一样。如果必须为 if 语句提供 true 或 false 值,则 match-case 语句可以以简洁的方式与对象的形状/结构进行匹配。请考虑 PEP 中的以下示例:

def make_point_3d(pt):
    match pt:
        case (x, y):
            return Point3d(x, y, 0)
        case (x, y, z):
            return Point3d(x, y, z)
        case Point2d(x, y):
            return Point3d(x, y, 0)
        case Point3d(_, _, _):
            return pt
        case _:
            raise TypeError("not a point we support")
Run Code Online (Sandbox Code Playgroud)

它不仅检查 的结构pt,还解压其中的值并根据需要将它们分配给x// 。yz