3 回答
TA贡献1827条经验 获得超9个赞
您可以使用列表理解:
list1 = [{'key1': 'item1'}, {'key2': 'item2'}]
list2 = [{'key1': 'item1'}, {'key2': 'item2'}, {'key3': 'item3'}]
print([x for x in list2 if x not in list1])
哪个会给 [{'key3': 'item3'}]
TA贡献1804条经验 获得超3个赞
你可以set()像这个例子一样使用理解:
def get_diff(elm1, elm2):
a = set((m, n) for k in elm1 for m, n in k.items())
b = set((m, n) for k in elm2 for m, n in k.items())
if len(b) > len(a):
return dict(b - a)
return dict(a - b)
list1 = [{'key1': 'item1'}, {'key2': 'item2'}]
list2 = [{'key1': 'item1'}, {'key2': 'item2'}, {'key3': 'item3'}]
get_diff(list1, list2)
输出:
{'key3': 'item3'}
TA贡献1821条经验 获得超4个赞
in_list1_not_in_list2 = [i for i in list1 if i not in list2]
in_list2_not_in_list1 = [i for i in list2 if i not in list1]
添加回答
举报