如何在匹配案例中执行其他(默认)?
How to do an else (default) in match-case?
Python recently has released match-case in version 3.10。问题是我们如何在 Python 中进行默认情况?我可以 if/elif
但不知道该怎么做。下面是代码:
x = "hello"
match x:
case "hi":
print(x)
case "hey":
print(x)
default:
print("not matched")
这是我自己添加的 default
。我想知道在 Python.
中执行此操作的方法
您可以在 Python 中定义默认情况。为此you use a wild card (_
)。下面的代码演示了它:
x = "hello"
match x:
case "hi":
print(x)
case "hey":
print(x)
case _:
print("not matched")
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
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
Python recently has released match-case in version 3.10。问题是我们如何在 Python 中进行默认情况?我可以 if/elif
但不知道该怎么做。下面是代码:
x = "hello"
match x:
case "hi":
print(x)
case "hey":
print(x)
default:
print("not matched")
这是我自己添加的 default
。我想知道在 Python.
您可以在 Python 中定义默认情况。为此you use a wild card (_
)。下面的代码演示了它:
x = "hello"
match x:
case "hi":
print(x)
case "hey":
print(x)
case _:
print("not matched")
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
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