如何在Python 3.10中使用多个匹配项来匹配(类似于其他语言中的switch)?

66

我正在尝试使用类似下面所示的函数中的多个案例,以便我能够在Python 3.10中使用match语句执行多个案例

def sayHi(name):
    match name:
        case ['Egide', 'Eric']:
            return f"Hi Mr {name}"
        case 'Egidia':
            return f"Hi Ms {name}"
print(sayHi('Egide'))

即使我去掉方括号,它仍然返回None而不是消息。


1
https://www.python.org/dev/peps/pep-0635/#or-patterns, https://www.python.org/dev/peps/pep-0636/#or-patterns, https://docs.python.org/3/whatsnew/3.10.html#pep-634-structural-pattern-matching - jonrsharpe
2个回答

116

1
如果您已经有了列表(并且需要在更多地方使用它),该怎么办?您是否可以从列表中创建'Egide' | 'Eric'这种模式?或者在这种情况下使用if语句更好? - Ruben
1
@Ruben 这似乎更适合使用 if 语句的情况。 - khelwood
1
@Ruben 你可以使用 guard 来实现:case name if name in male_names:。在 Blake's answer 中还有更多信息。 - Jacktose
也要小心不要意外地使用(x,y)!那个匹配字面元组的,我犯过那个错误很多次,最后总是回到这个答案上来。。 - undefined

21
您可以使用|)将['Egide', 'Eric']替换为'Egide' | 'Eric',但您也可以使用守卫来匹配属于迭代器或容器的元素,具体方式如下:
CONSTANTS = ['a','b', ...] # a (possibly large) iterable

def demo(item):
    match item:
        case item if item in CONSTANTS:
            return f"{item} matched"
        case _:
            return f"No match for {item}"

5
“case other” 应该改为 “case _” 吗? - odigity
6
嗨@odigity--它只是一个未使用的变量名称,所以您可以随意将其命名为任何内容。 - Blake
4
@blake,同意,但(非)官方约定似乎是使用下划线表示默认情况。 - Tom Pohl
1
@TomPohl @Black 在case othercase _之间有一个区别,PEP 634以及这里(https://earthly.dev/blog/structural-pattern-matching-python)都有解释。前者是一种捕获匹配,并将匹配绑定到一个新变量`other`,而后者是通配符匹配。如果没有其他条件,两者始终成功。 - interDist
1
@TomPohl @Black 在case othercase _之间有一个区别,PEP 634以及这里(https://earthly.dev/blog/structural-pattern-matching-python)有解释。前者是一个捕获匹配,并将匹配绑定到一个新变量`other`,而后者是一个通配符匹配。如果没有其他条件,两者都会成功。 - undefined
1
@interDist,同意,但由于other在案例主体中未被使用,我仍然建议_. - Tom Pohl

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接