python - 在不使用集合的情况下,在嵌套的 for 循环中对 dict 和 list 中的项目进行成员资格检查?

标签 python python-3.x

我有一个有序的字典:

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

potential_matches 列表:[red, blue, one]

我想将这些潜在匹配排序到两个列表之一:
正确 = []不正确 = []

如果潜在匹配是字典中某个键的关键字,则它进入正确,否则进入不正确

这个例子的结果应该是:
正确 = [blue]不正确 = [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)  

本质上,所有不匹配的剩余单词都应该简单地转到另一个列表。

虽然有效,但似乎效率不高。它必须是一个列表以保持顺序,并且列表可以重叠。

注意:我之前问过一个类似的问题,尽管在那种情况下,情况和答案要求使用 python 集,因为项目是唯一的。

最佳答案

v=[x for i in od.values() for x in list(i.values())[0]]
l=['red','blue','one']
correct=[i for i in v if i in l]
incorrect=[i for i in l if i not in v]
print(correct)
print(incorrect)

输出:

['blue']
['red', 'one']

关于python - 在不使用集合的情况下,在嵌套的 for 循环中对 dict 和 list 中的项目进行成员资格检查?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51977511/

相关文章:

python - 无法访问 postgresql 表

字典特定值的 Python 类型提示

python - 安装适用于 Python 的 MATLAB 引擎

Python:按名称传递参数

Python:按时间间隔对结果进行分组

python-3.x - 将 PyFolio 与 Pandas 一起使用

Python 3.0 `wsgiref` 服务器无法运行

python - Pandas 创建一个数据框,其条目是另一个数据框的行之间的关系?

python - 如何在 multiprocessing.dummy.Pool 中单独命名线程?

python - 在某些条件下查找 pandas 的连续值