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

时间:2018-08-22 08:53:32

标签: python dictionary for-loop nested

试图使这项工作使我旋转:
我有命令的字典:

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

我有一个potential_matches的列表:[red, blue, one]

我要将这些潜在匹配项排序为两个列表之一:
correct = []incorrect = []

如果潜在匹配是字典中某个键之一的关键字,则将其放在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)  

列表不能重叠,并且必须具有唯一项,这就是elif中有这么多检查的原因。 它已经关闭了,但是最终发生的是,不正确的列表仍将包含来自正确列表的项目。

如何才能尽可能有效地解决此问题?

我听起来有点复杂,但是从本质上讲,所有不匹配的剩余单词都应该简单地转到其他列表。不过,我认为,这需要对potential_match列表和字典进行一次完整的操作。

1 个答案:

答案 0 :(得分: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

结果:

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

{'blue'}
{'one', 'red'}

可以通过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

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