Python 3.10模式匹配(PEP 634)- 字符串中的通配符

27
我有一个大的JSON对象列表,我想根据其中一个键的开头进行解析,并仅使用通配符匹配其余部分。 许多键都很相似,例如“matchme-foo”和“matchme-bar”。 有一个内置通配符,但它仅用于整个值,有点像“else”。 我可能会忽视某些事情,但我无法在建议书中找到任何解决方案:https://docs.python.org/3/whatsnew/3.10.html#pep-634-structural-pattern-matching 此外,在PEP-636中还有更多相关信息:https://www.python.org/dev/peps/pep-0636/#going-to-the-cloud-mappings 我的数据看起来像这样:
data = [{
          "id"     : "matchme-foo",
          "message": "hallo this is a message",
      },{
          "id"     : "matchme-bar",
          "message": "goodbye",
      },{
          "id"     : "anotherid",
          "message": "completely diffrent event"
      }, ...]

我希望能够做一些事情,可以匹配id而不必制作一长串的|

就像这样:

for event in data:
    match event:
        case {'id':'matchme-*'}: # Match all 'matchme-' no matter what comes next
            log.INFO(event['message'])
        case {'id':'anotherid'}:
            log.ERROR(event['message'])

它是Python相对较新的补充,因此还没有很多关于如何使用它的指南。

1个回答

36

你可以使用一个守卫

for event in data:
    match event:
        case {'id': x} if x.startswith("matchme"): # 守卫
            print(event["message"])
        case {'id':'anotherid'}:
            print(event["message"])

引用自官方文档

Guard

We can add an if clause to a pattern, known as a “guard”. If the guard is false, match goes on to try the next case block. Note that value capture happens before the guard is evaluated:

match point:
     case Point(x, y) if x == y:
         print(f"The point is located on the diagonal Y=X at {x}.")
     case Point(x, y):
         print(f"Point is not on the diagonal.")
另请参阅:
- [PEP 622 - Guards](link1) - [PEP 636 - Adding conditions to patterns](link2) - [PEP 634 - Guards](link3)

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