使用Python.get筛选多个值
我使用下面的代码来过滤json列表的数据使用Python.get筛选多个值,python,arrays,python-3.x,Python,Arrays,Python 3.x,我使用下面的代码来过滤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'),
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})
它过滤code==user1的数据
但是,如果代码有user1或error,我需要过滤数据。所有拥有代码的收件人都是每批的user1或error。如果我正确理解您的问题,并且您只需要两个值user1或error,则可以更改行
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")]