如何在匹配情况下执行 else (默认)?

far*_*att 50 python python-3.10 structural-pattern-matching

Python 最近在 3.10 版本中发布了 match-case。问题是我们如何在 Python 中实现默认情况?我可以做if/elif,但不知道还能做什么。下面是代码:

x = "hello"
match x:
    case "hi":
        print(x)
    case "hey":
        print(x)
    default:
        print("not matched")
Run Code Online (Sandbox Code Playgroud)

这是我default自己添加的。我想知道在 Python 中执行此操作的方法。

Pri*_*mza 74

您可以在 Python 中定义默认情况。为此,您可以使用通配符( _)。下面的代码演示了它:

x = "hello"
match x:
    case "hi":
        print(x)
    case "hey":
        print(x)
    case _:
        print("not matched")
Run Code Online (Sandbox Code Playgroud)