【发布时间】: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 列表和字典。
【问题讨论】:
-
您的示例似乎运行良好:repl.it/repls/PeruBlackMineral
-
@AlexHall 无法在本地工作.. 奇怪。
标签: python dictionary for-loop nested