我有一个命令:
import collections
collections.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)
从本质上讲,所有不匹配的其余单词都应简单地转到另一个列表。
尽管有效,但似乎效率不高。它必须是一个列表以保留顺序,并且列表可能会重叠。
注意:我以前也问过类似的问题,尽管在这种情况下,情况和答案都要求使用python集,因为项是唯一的。
答案 0 :(得分:3)
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']
答案 1 :(得分:1)
您首先需要从OrderedDict
获取值,然后可以使用简单的列表推导来获取值。要获取值,可以将operator.itemgetter
与itertools.chain
一起使用。这将为您提供一个简单的值列表。
>>> from itertools import chain
>>> from operator import itemgetter
>>> values = list(chain(*map(itemgetter('keyword'), list(d.values()))))
>>> values
>>> ['yellow', 'blue', 'lock', 'door']
>>> m = ['red', 'blue', 'one']
>>> correct = [s for s in m if s in values]
>>> correct
>>> ['blue']
>>> incorrect = [a for a in m if a not in values]
>>> incorrect
>>> ['red', 'one']