【问题标题】:How do I check membership of items in a dict and list, within nested for loops?如何在嵌套的 for 循环中检查字典和列表中项目的成员资格?
【发布时间】:2019-01-28 11:53:11
【问题描述】:

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

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 列表和字典。

【问题讨论】:

标签: python dictionary for-loop nested


【解决方案1】:

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

但是,由于您正在处理独特项目的集合,因此您可以使用 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 循环的编写方式一致。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-13
    • 2019-09-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-03
    • 2021-07-07
    相关资源
    最近更新 更多