【发布时间】:2010-08-20 09:51:19
【问题描述】:
我有两个 Python 字典列表,entries9 和 entries10。我想比较这些项目并将联合项目写入一个名为joint_items 的新列表。我还想将不匹配的项目保存到两个新列表中,unmatched_items_9 和 unmatched_items_10。
这是我的代码。获取joint_items 和unmatched_items_9(在外部列表中)非常容易:但是我如何获取unmatched_items_10(在内部列表中)?
for counter, entry1 in enumerate(entries9):
match_found = False
for counter2,entry2 in enumerate(entries10):
if match_found:
continue
if entry1[a]==entry2[a] and entry1[b]==entry2[b]: # the dictionaries only have some keys in common, but we care about a and b
match_found = True
joint_item = entry1
joint_items.append(joint_item)
#entries10.remove(entry2) # Tried this originally, but realised it messes with the original list object!
if match_found:
continue
else:
unmatched_items_9.append(entry1)
性能并不是真正的问题,因为它是一次性脚本。
【问题讨论】:
-
我认为您可以在内部循环中将
if match_found: continue替换为if match_found: break(末尾)。 -
好点@SiggyF!是的,我可以。