如何在python中统一dict列表

ram*_*h.c 20 python

我有一个清单:

d = [{'x':1, 'y':2}, {'x':3, 'y':4}, {'x':1, 'y':2}]
Run Code Online (Sandbox Code Playgroud)

{'x':1, 'y':2} 不止一次我想从列表中删除它.我的结果应该是:

 d = [{'x':1, 'y':2}, {'x':3, 'y':4} ]
Run Code Online (Sandbox Code Playgroud)

注意: list(set(d))这里没有工作抛出错误.

GWW*_*GWW 23

如果你的价值是可以清洗的,这将有效:

>>> [dict(y) for y in set(tuple(x.items()) for x in d)]
[{'y': 4, 'x': 3}, {'y': 2, 'x': 1}]
Run Code Online (Sandbox Code Playgroud)

编辑:

我尝试了它没有重复,它似乎工作正常

>>> 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}]
Run Code Online (Sandbox Code Playgroud)

>>> d = [{'x':1,'y':2}]
>>> [dict(y) for y in set(tuple(x.items()) for x in d)]
[{'y': 2, 'x': 1}]
Run Code Online (Sandbox Code Playgroud)


小智 8

Dicts不可清洗,所以你不能把它们放在一套.一种相对有效的方法是将对(key, value)转换为元组并对这些元组进行散列(随意消除中间变量):

tuples = tuple(set(d.iteritems()) for d in dicts)
unique = set(tuples)
return [dict(pairs) for pairs in unique]
Run Code Online (Sandbox Code Playgroud)

如果值并不总是可以使用,则根本不可能使用集合,并且您必须使用in每元素检查的O(n ^ 2)方法.


Joc*_*zel 6

避免这整个问题,而是使用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)
Run Code Online (Sandbox Code Playgroud)


Fre*_*ihl 5

一个简单的循环:

tmp=[]

for i in d:
    if i not in tmp:
        tmp.append(i)        
tmp
[{'x': 1, 'y': 2}, {'x': 3, 'y': 4}]
Run Code Online (Sandbox Code Playgroud)

  • 实际上只有 4 个(不计算打印数)。:-) 关于可读性,情人眼里出西施 :-) (3认同)
  • 5 行 vs. 1 行(在 GWW 的回答中),甚至可读性不一样……这就是为什么在适当的剂量下简洁并不是邪恶的原因。 (2认同)