【问题标题】:How to remove certain dictionaries from list?如何从列表中删除某些词典?
【发布时间】:2021-07-08 07:21:33
【问题描述】:

我有一个字典列表:

list_with_dicts = [{"nbr": 1, "id": 11}, {"nbr": 2, "id": 13}, {"nbr": 3, "id": 15}, ...]

我有一个列表,其中包含我想用字典从列表中删除的所有 id:s:

ids = [11, 15, ...]

我怎样才能有效地做到这一点?我看到了这个答案here,但是它不包括我是否需要遍历ids 列表。

【问题讨论】:

  • 您了解该答案中的代码吗?您是否特别了解它是如何测试 id 值的?你能想出一种方法来重写id 测试来检查id 是否是in 你的ids 列表(提示,提示)?
  • 类似于@KarlKnechtel。但我的问题是我需要在迭代list_with_dicts 的同时迭代ids 列表。不知道该怎么做。
  • 您不会遍历 id,而是使用 d["id"] in ids 检查“id”是否在 id 中
  • 这能回答你的问题吗? Remove dictionary from list

标签: python list loops dictionary


【解决方案1】:

您不必遍历ids 列表,至少不必显式地遍历。遍历字典列表并使用in 检查id 值是否在ids 列表中。如果您遍历列表的副本,您可以使用 remove(dict) 从列表中删除字典

list_with_dicts = [{"nbr": 1, "id": 11}, {"nbr": 3, "id": 15}, {"nbr": 2, "id": 13}]
ids = [11, 15]

for d in list_with_dicts[:]:
    if d['id'] in ids:
        list_with_dicts.remove(d)

print(list_with_dicts) # [{'nbr': 2, 'id': 13}]

如果您想保留原始列表,可以使用列表推导构建一个新列表

new_list_with_dicts = [d for d in list_with_dicts if d['id'] not in ids]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-07-12
    • 1970-01-01
    • 2019-12-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-23
    相关资源
    最近更新 更多