python – 如何在嵌套for循环中检查字典和列表中的项的成员资格
试图让这项工作让我头晕目眩:
我有一个有序的词典: OrderedDict([('key',{'keyword': {'blue','yellow'}),('key1',{'keyword': {'lock','door'})]) 我有一个potential_matches列表:[红色,蓝色,一个] 我想将这些潜在的匹配命名为两个列表中的一个: 如果潜在匹配是dict中某个键的关键字,那么它进入正确,否则进入不正确. 这个例子的结果应该是: 这是我尝试过的: 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列表完整运行&但是,我认为.. 解决方法
我运行它时你的逻辑工作正常,所以可能有一些你没有提供的逻辑导致错误.
但是,由于您正在处理独特项的集合,因此您可以使用set而不是list更高效地实现逻辑. 此外,不是循环使用potential_matches,而是遍历字典并将项目添加到正确的集合中.这将您的复杂度从O(m * n)降低到O(n),即最低级别字典值中的元素数量. 然后,在最后,使用set.difference或syntactic sugar – 来计算不正确的集合.这是一个演示: from collections import OrderedDict d = OrderedDict([('key','yellow'}}),'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'} 通过集合理解可以实现更高效的版本: potential_matches = {'red','one'} correct = {w for v in d.values() for w in v['keyword'] if w in potential_matches} incorrect = potential_matches - correct 请注意,嵌套集合理解的结构与编写详细嵌套for循环的方式一致. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |