python 字典列表/列表套字典 去重重复的字典数据
原文引自:https://blog.csdn.net/weixin_37994148/article/details/99731818
第一种
def deleteDuplicate(li):
func = lambda x, y: x if y in x else x + [y]
li = reduce(func, [[], ] + li)
return li关于reduce(),请看http://docs.python.org/2/library/functions.html#reduce
第二种
def deleteDuplicate(li):
temp_list = list(set([str(i) for i in li]))
li=[eval(i) for i in temp_list]
return li第三种方法(python2中出错)
[dict(t) for t in set([tuple(d.items()) for d in li])]
# 解释
li 是原始列表
d 是列表中的一个字典
t 是从字典中创建的元组之一
l = [{‘a‘: 123, ‘b‘: 1234},
{‘a‘: 3222, ‘b‘: 1234},
{‘a‘: 123, ‘b‘: 1234}]
seen = set()
new_l = []
for d in l:
t = tuple(d.items())
if t not in seen:
seen.add(t)
new_l.append(d)
print new_l