首页 > 解决方案 > 使用 Python.get 过滤多个值

问题描述

我正在使用下面的代码来过滤 json 列表的数据。

new_list = list()
for lot in json_ls:
    recs = lot.get('recipients')
    lot_recipients = [rec for rec in recs if rec.get("code") == "user1"]
    if lot_recipients:
        new_list.append({"lot_number": lot.get('lot_number'),
                         "recipients": lot_recipients})

它过滤代码==“user1”的数据

但是,如果代码具有“user1”或“错误”,我需要过滤数据。对于每个批次,所有拥有代码的收件人都是“user1”或“错误”。

标签: pythonarrayspython-3.x

解决方案


如果我正确理解您的问题,并且您只需要两个值(user1error),您可以更改该行

lot_recipients = [rec for rec in recs if rec.get("code") == "user1"]

lot_recipients = [rec for rec in recs if rec.get("code") in ("user1", "error")]

推荐阅读