我得到了一个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的一个相对较新的补充,因此关于如何使用它的指南还不多.

推荐答案

你可以使用100:

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年前的话,

100

我们可以在模式中添加一个if子句,称为"guard".If the guard is 101, match goes on to try the next 102 block.注意

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.x相关问答推荐

为什么vs code返回错误—LocaleError:int对象没有属性where,但相同的代码运行在Google Colab上没有任何问题''''

Python3和请求-超文本标记语言:试图抓取一个网站-没有取回真正的超文本标记语言代码

当条件第一次出现时将行标记为True,如果按顺序重复则标记为False

selenium 无法执行网站上最简单的功能

Python 舍入数字不准确

在Pandas中,根据另一列中的重复值将数据分组为一列

Sunburst 折线图可视化

无法提出给定 for 循环的原因 (Python 3.11)

如何通过 GitLab V4 api 列出 gitlab 项目中的所有项目变量

numpy是如何添加@运算符的?

如何知道Pandas 列中的每个后续值是否都大于前面的值? Python相关

Python多进程:运行一个类的多个实例,将所有子进程保留在内存中

如何查找 tensorflow.python.data.ops.dataset_ops.MapDataset 对象的大小或形状,make_csv_dataset 的输出

保存 StandardScaler() 模型以用于新数据集

为 python3 安装 opencv

判断对 python 3 支持的要求

python - 错误 R10(启动超时)-> Web 进程未能在启动后 60 秒内绑定到 $PORT

如何从 Python 3 导入 FileNotFoundError?

如何将文档字符串放在 Enums 上?

有效地判断一个元素是否在列表中至少出现 n 次