简体   繁体   English

结构模式匹配 Python - 匹配集/Frozenset

[英]Structural Pattern Matching Python - Matching a Set / Frozenset

I've been playing around with Structural Pattern Matching in Python 3.10 and can't figure out how to get it to match a set.我一直在玩 Python 3.10 中的结构模式匹配,但无法弄清楚如何让它匹配一个集合。 For example I've tried:例如我试过:

a = {1,2,3}

match a:
    case set(1,2,3):
        print('matched')

and I've tried:我试过:

a = {1,2,3}

match a:
    case set([1,2,3]):
        print('matched')

As well as:也:

a = {1,2,3}

match a:
    case [1,2,3] if isinstance(a, set):
        print('matched')

I'm guessing there is a way to do this since we can match other objects and I'm just missing the correct syntax but I can't think of what else to try.我猜有一种方法可以做到这一点,因为我们可以匹配其他对象,我只是缺少正确的语法,但我想不出还有什么可以尝试的。 Any help would be appreciated!任何帮助,将不胜感激! Thanks!谢谢!

This isn't really how structural pattern matching is meant to be used;这并不是结构模式匹配的真正用途。 the pattern you're matching is more about value than structure .您匹配的模式更多的是关于value而不是structure Because of this, I think you'll find that the equivalent if form is much more readable:因此,我认为您会发现等效的if形式更具可读性:

if a == {1, 2, 3}:
    print('matched')

With that said...照这样说...

Python 3.10 doesn't have syntactic support for matching sets; Python 3.10 不支持匹配集的语法; it only has dedicated "display" syntax for sequences and mappings.它只有序列和映射的专用“显示”语法。 I think we briefly considered this, but ultimately dropped it because wasn't very useful or intuitive (and it's easy enough to add in a later version).我认为我们简要地考虑了这一点,但最终放弃了它,因为它不是很有用或不直观(而且很容易在以后的版本中添加)。

Fortunately, it's possible to match any value by equality using a qualified (or "dotted") name.幸运的是,可以使用限定(或“点”)名称通过相等来匹配任何值。 If you need to match a set as part of a larger pattern or match block, that's probably the best way to do it:如果您需要将集合作为更大模式或match块的一部分进行匹配,这可能是最好的方法:

class Constants:
    SET_123 = {1, 2, 3}

match a:
    case Constants.SET_123:
        print('matched')

It can also be combined with a class pattern if you only want to match sets (and not, for example, frozensets):如果您只想匹配集合(而不是,例如,frozensets),它也可以与 class 模式结合使用:

match a:
    case set(Constants.SET_123):
        print('matched')

Since the match construct doesn't use set equality to compare sets, you will need to use a guard to do it explicitly:由于match构造不使用集合相等来比较集合,因此您需要使用守卫来明确地进行比较:

a = {1,2,3}

match a:
    case _ if a == set([1,2,3]): 
        print('matched')

It's unintutive that sets aren't compared with set equality by default.默认情况下不将集合与集合相等进行比较是不直观的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM