【问题标题】:What's the efficient way to filter a python dictionary based on whether an element in a value list exists?根据值列表中的元素是否存在来过滤python字典的有效方法是什么?
【发布时间】:2021-12-04 00:36:42
【问题描述】:

我有一个这样定义的字典(表):

table = {"id": [1, 2, 3]}, {"file": ['good1.txt', 'bad2.txt', 'good3.txt']}

我有一个应该删除的不良候选人列表:

to_exclude = ['bad0.txt', 'bad1.txt', 'bad2.txt']

我希望根据我的表的一行中的文件是否可以在 to_exclude 中找到来过滤表。

filtered = {"id": [1, 2]}, {"file": ['good1.txt', 'good3.txt']}

我想我可以使用 for 循环来逐一检查条目,但我想知道解决这个问题的最高效的 p​​ython 方式是什么。

有人可以提供一些指导吗?谢谢。

【问题讨论】:

  • 我删除了我的答案,因为我误读了这个问题。这是错误的。将重做。
  • 您的数据结构无效。你的意思是它是一个字典列表还是一个字典?

标签: python data-structures


【解决方案1】:

我假设你写错了你的数据结构。你有一套两本字典,这是不可能的。 (字典不可散列)。我希望您的实际数据是:

data = {"id": [1, 2, 3], "file": [.......]}

一个有两个键的字典。

所以对我来说,最简单的是:

# Create a set for faster testing
to_exclude_set = set(to_exclude)
# Create (id, file) pairs for the pairs we want to keep
pairs = [(id, file) for id, file in zip(data["id"], data["file"])
          if file not in to_exclude_set]
# Recreate the data structure
result = { 'id': [_ for id, _ in pairs],
           'file': [_ for _, file in pairs] }

【讨论】:

  • 谢谢。有用。我还修复了最初的问题。
猜你喜欢
  • 1970-01-01
  • 2021-11-08
  • 2010-09-27
  • 1970-01-01
  • 1970-01-01
  • 2015-05-17
  • 1970-01-01
  • 1970-01-01
  • 2021-09-23
相关资源
最近更新 更多