我有一个有序的字典:
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/