我设置了一个
match...case...
循环,如果任何一种情况匹配,我想运行一些代码。我想我可以通过像下面这样指定一个变量来做到这一点,但我想知道是否有更短的方法来做到这一点,因为这似乎过于冗长。
这里有一些示例代码,简而言之,我需要做的事情:
def foo(x):
c = 0
match x:
case "Hello,":
a()
c = 1
case "World!":
b()
c = 1
case "foobar":
c()
c = 1
if c == 1:
print("Something happened")
else:
print("Something didn't happen :(")
我还可以在每个
case
中运行我的函数:
case "Hello,":
a()
print("Something happened")
(etc...)
但是,这似乎多余,我想知道是否有更优雅的解决方案。
我的2克拉
def a():
print("On 'a' func")
def b():
print("On 'b' func")
def c():
print("On 'c' func")
def foo(x):
if x in cmd:
cmd[x]()
print(f"Something happened on '{x}': {cmd[x]}")
else:
print(f"Something didn't happen :( on '{x}'")
cmd = {"Hello,": a, "World!": b, "foobar": c}
foo("World!")
foo("bar")
On 'b' func
Something happened on 'World!': <function b at 0x7fd52fe653a0>
Something didn't happen :( on 'bar'