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

问题描述 投票:0回答:1

我有一个很大的 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 的一个相对较新的补充,因此目前还没有很多关于如何使用它的指南。

python json python-3.x pattern-matching python-3.10
1个回答
36
投票

您可以使用守卫

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

引用官方文档

守卫

我们可以向模式添加一个

if
子句,称为“guard”。 如果 守卫是
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.")

另请参阅:

© www.soinside.com 2019 - 2024. All rights reserved.