3

Python最近在python 3.10版本中发布了match case。问题是我们如何在python中为case做一个默认值。我可以做if elif但不知道怎么做。下面是代码。

x = "hello"
match x:
     case "hi":
          print(x)
     case "hey":
          print(x)
     default:
          print("not matched")

我自己添加了这个默认值。我想知道在 python 中执行此操作的方法

4

3 回答 3

6

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

x = "hello"
match x:
     case "hi":
          print(x)
     case "hey":
          print(x)
     case _:
          print("not matched")
于 2021-08-16T14:08:29.527 回答
1
match subject:
    case <pattern_1>:
        <action_1>
    case <pattern_2>:
        <action_2>
    case <pattern_3>:
        <action_3>
    case _:
        <action_wildcard>

参见:https ://docs.python.org/3.10/whatsnew/3.10.html#syntax-and-operations

于 2021-08-16T14:09:02.717 回答
-2
for thing in [[1,2],[2,11],[12,14,13],[10],[10,20,30,40,50]]:
match thing:
    case [x]:
        print(f"single value: {x}")
    case [x,y]:
        print(f"two values: {x} and {y}")
    case [x,y,z]:
        print(f"three values: {x}, {y} and {z}")       
    case _: # change this in default 
        print("too many values")

如果您想阅读并获得更多理解:https ://towardsdatascience.com/pattern-matching-in-python-3-10-6124ff2079f0

于 2021-08-16T14:12:41.703 回答