20

我得到了一大堆 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 的事情,而不必制作一长串的|'s.

像这样的东西:

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 的一个相对较新的补充,因此关于如何使用它的指南并不多。

4

1 回答 1

29

您可以使用警卫

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

引用官方文档

警卫

我们可以在if模式中添加一个子句,称为“守卫”。如果守卫是false,比赛继续尝试下一个case。请注意,值捕获发生在评估防护之前:

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.")

也可以看看:

于 2021-11-25T12:52:44.277 回答