如何在嵌套for循环中检查dict和列表中项目的成员资格?

Cas*_*per 3 python dictionary for-loop nested

试图让这项工作让我头晕目眩:
我有一个有序的词典:

OrderedDict([('key', {'keyword': {'blue', 'yellow'}), ('key1', {'keyword': {'lock', 'door'})])
Run Code Online (Sandbox Code Playgroud)

我有一个清单potential_matches:[red, blue, one]

我想将这些潜在的匹配命名为两个列表之一:
correct = []incorrect = []

如果潜在匹配是dict中某个键的关键字,则它会进入correct,否则它会进入incorrect.

这个例子的结果应该是:
correct = [blue],incorrect = [red, one]

这是我尝试过的:

correct = []  
incorrect = []  
for word in potential_matches:
    for key, value in ordered_dict.items():
        if word in value["keyword"] and word not in correct:
            correct.append(word)
        elif word not in value["keyword"] and word not in correct and word not in incorrect:
            incorrect.append(word)  
Run Code Online (Sandbox Code Playgroud)

列表不能有重叠,必须有唯一的项目,这就是为什么有这么多的检查elif.
它很接近,但最终发生的是不正确的列表仍然会有正确列表中的项目.

如何尽可能有效地解决这个问题?

我觉得它听起来有点复杂,但基本上,所有剩下的不匹配的单词应该只是转到另一个列表.这需要一个完整的potential_match列表和字典,但我认为..

jpp*_*jpp 6

我运行它时你的逻辑工作正常,所以可能有一些你没有提供的逻辑导致错误.

但是,由于您正在处理独特项目的集合,因此您可以使用set而不是更有效地实现逻辑list.

此外,不是循环,而是potential_matches遍历字典并将项目添加到correct集合中.这会将您的复杂度从O(m*n)降低到O(n),即最低级别字典值中的元素数量.

然后,在最后,使用set.difference或语法糖-来计算incorrect集合.这是一个演示:

from collections import OrderedDict

d = OrderedDict([('key', {'keyword': {'blue', 'yellow'}}),
                 ('key1', {'keyword': {'lock', 'door'}})])

potential_matches = {'red', 'blue', 'one'}

correct = set()
for v in d.values():
    for w in v['keyword']:
        if w in potential_matches:
            correct.add(w)

incorrect = potential_matches - correct
Run Code Online (Sandbox Code Playgroud)

结果:

print(correct, incorrect, sep='\n')

{'blue'}
{'one', 'red'}
Run Code Online (Sandbox Code Playgroud)

通过set理解可以实现更高效的版本:

potential_matches = {'red', 'blue', 'one'}
correct = {w for v in d.values() for w in v['keyword'] if w in potential_matches}
incorrect = potential_matches - correct
Run Code Online (Sandbox Code Playgroud)

请注意,嵌套集合理解的结构与for编写详细嵌套循环的方式一致.