Python 3.10模式匹配(PEP 634)-字符串中的通配符 [英] Python 3.10 pattern matching (PEP 634) - wildcard in string

查看:37
本文介绍了Python 3.10模式匹配(PEP 634)-字符串中的通配符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我得到了一个很大的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的一个相对较新的添加,所以关于如何使用它的指南还不多。

推荐答案

您可以使用

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

引用自official documentation

警卫

我们可以向模式添加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.")

另请参阅:

这篇关于Python 3.10模式匹配(PEP 634)-字符串中的通配符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆