python - 使用 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”或“错误”。
解决方案
如果我正确理解您的问题,并且您只需要两个值(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")]
推荐阅读
- event-handling - Shopware 6:商务活动问题、多个订单确认
- c - 如何更改特定内存地址中的值?
- ios - Swift 中存储属性和计算属性的值
- r - 如何在 R 中的时间序列图中仅包含交易日
- elixir - 在 Elixir 中最后一个斜杠后删除字符串
- javascript - Node.js 脚本在本地工作,但在 firebase 服务上不能在本地工作?
- reactjs - 我如何在反应原生钩子中使背景颜色动态
- python - 在 python 中可视化数据
- c# - 没有代理的 HttpWebRequest 很慢
- corda - 使用 ZipEntry 重复附件异常 Corda