我有两个这样的列表:
list1 = [{'id':1, 'name':'foo', 'age':20}, {'id':2, 'name':'foo', 'age':20}]
list2 = [{'id':2, 'created':'2004-12-23'}, {'id':12, 'created':'2004-12-23'},
{'id':1, 'created':'2004-12-23'}]
list1 = [{'id':1, 'name':'foo', 'age':20, 'match':True},
{'id':2, 'name':'foo', 'age':20, 'match':True}]
如果list1和list2的id匹配,我想将匹配添加到相应的列表中。我怎么能有效地做到这一点?
答案 0 :(得分:5)
set2 = set(x['id'] for x in list2)
for entry in list1:
if entry['id'] in set2:
entry['match'] = True
OR
set2 = set(x['id'] for x in list2)
for entry in list1:
entry['match'] = entry['id'] in set2