繁体   English   中英

根据值列表中的元素是否存在来过滤 python 字典的有效方法是什么?

[英]What's the efficient way to filter a python dictionary based on whether an element in a value list exists?

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

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 循环来逐一检查条目,但我想知道解决这个问题的最高效的 python 方式是什么。

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

最有效的做法是将to_exclude转换为一个集合。 然后进行简单的搜索

# just so things are efficient
to_exclude_set = set(to_exclude)

table = {key: [value for value in values if value not in to_exclude_set] 
         for key, values in table.items()
        }

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

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] }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM