如何在Python中去重字典列表
我有一个列表:
d = [{'x':1, 'y':2}, {'x':3, 'y':4}, {'x':1, 'y':2}]
里面有个内容 {'x':1, 'y':2}
出现了很多次,我想把它从列表中去掉。最后的结果应该是:
d = [{'x':1, 'y':2}, {'x':3, 'y':4} ]
注意:
list(set(d))
在这里不管用,会报错。
6 个回答
7
别纠结这个问题了,直接用命名元组(namedtuples)就行。
from collections import namedtuple
Point = namedtuple('Point','x y'.split())
better_d = [Point(1,2), Point(3,4), Point(1,2)]
print set(better_d)
8
字典是不可哈希的,所以你不能把它们放进集合里。一个相对高效的方法是把(键, 值)
对转换成元组,然后对这些元组进行哈希处理(你可以省略中间变量):
tuples = tuple(set(d.iteritems()) for d in dicts)
unique = set(tuples)
return [dict(pairs) for pairs in unique]
如果值并不总是可哈希的,那么使用集合就完全不可能了,你可能需要使用每个元素都进行in
检查的O(n^2)方法。
33
如果你的值是可以被哈希的,这样做就可以:
>>> [dict(y) for y in set(tuple(x.items()) for x in d)]
[{'y': 4, 'x': 3}, {'y': 2, 'x': 1}]
补充:
我试过没有重复的值,结果看起来没问题
>>> d = [{'x':1, 'y':2}, {'x':3, 'y':4}]
>>> [dict(y) for y in set(tuple(x.items()) for x in d)]
[{'y': 4, 'x': 3}, {'y': 2, 'x': 1}]
还有
>>> d = [{'x':1,'y':2}]
>>> [dict(y) for y in set(tuple(x.items()) for x in d)]
[{'y': 2, 'x': 1}]