我运行它时你的逻辑工作正常,所以可能有一些你没有提供的逻辑导致错误.
但是,由于您正在处理独特项的集合,因此您可以使用set而不是list更高效地实现逻辑.
此外,不是循环使用potential_matches,而是遍历字典并将项目添加到正确的集合中.这将您的复杂度从O(m * n)降低到O(n),即最低级别字典值中的元素数量.
然后,在最后,使用set.difference或syntactic sugar – 来计算不正确的集合.这是一个演示:
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
结果:
print(correct, incorrect, sep='\n')
{'blue'}
{'one', 'red'}
通过集合理解可以实现更高效的版本:
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
请注意,嵌套集合理解的结构与编写详细嵌套for循环的方式一致.