1
VYSE 2013-08-21 23:01:11 +08:00
你把{}变成()
t1 = [('a',1),('a',1),('b',2)] 一个dict不久搞定了? d1 = dict(t1) |
2
ipconfiger 2013-08-21 23:08:00 +08:00 1
[{k:v} for k,v in dict([list(d.iteritems())[0] for d in t1]).iteritems()]
搞定收工 |
3
pinkman OP @ipconfiger 厉害!但看起来好难懂啊,我还是用最简单我原来的方法算了
|
4
saturnisbig 2013-08-21 23:13:35 +08:00
可以参考stackoverflow上的回答:http://stackoverflow.com/questions/9427163/remove-duplicate-dict-in-list-in-python
|
5
ipconfiger 2013-08-21 23:51:29 +08:00
@pinkman 随手写的写复杂了点
[{k:v} for k,v in dict([d.items()[0] for d in t1]).items()] 简化后就这样了,其实dict([d.items()[0] for d in t1]).items() 以外的部分纯粹是为了把列表内还原成一个个字典 |
6
jokaye 2013-08-22 09:35:06 +08:00 1
[t11.append(t) for t in t1 if t not in t11] ?
|
7
pinkman OP @jokaye 原来如此,还是需要先生成个t11 = []的空字典,随后的list表达式就好写了,之前我就一直在想不自己先定义t11(因为考虑到列表表达式本来就要生成列表),所以才老是想不出来,现在清楚了,感谢jokaye
|
8
mengzhuo 2013-08-22 11:37:00 +08:00
[t11.append(t) for t in l if t not in t11]
1000000 loops, best of 3: 793 ns per loop # 不过话说这么个复杂度是2n吧 [dict(t) for t in set([tuple(d.items()) for d in l])] 100000 loops, best of 3: 9.25 us per loop [{k:v} for k,v in dict([list(d.iteritems())[0] for d in t1]).iteritems()] 100000 loops, best of 3: 10.4 us per loop [{k:v} for k,v in dict([d.items()[0] for d in t1]).items()] 100000 loops, best of 3: 5.01 us per loop # 这个很漂亮 --------------------------- 升级一下测试: t2 = [{random.randint(0, 4095):1} for k in xrange(9999)] len([d for d in t2 if t2.count(d) > 1]) # 这次随机出9144项重复的 [t22.append(t) for t in t2 if t not in t22] 1 loops, best of 3: 1.54 s per loop # 直接跪了 = = [dict(t) for t in set([tuple(d.items()) for d in t2])] 10 loops, best of 3: 21.9 ms per loop [{k:v} for k,v in dict([list(d.iteritems())[0] for d in t2]).iteritems()] 10 loops, best of 3: 26 ms per loop [{k:v} for k,v in dict([d.items()[0] for d in t2]).items()] 100 loops, best of 3: 11.4 ms per loop # 用iter,会更好 [{k:v} for k,v in dict([d.items()[0] for d in t2]).iteritems()] 100 loops, best of 3: 10.7 ms per loop |
9
mengzhuo 2013-08-22 11:57:21 +08:00
我觉得黑魔法了的一种方法:
[{k:v} for k,v in dict([d.iteritems().next() for d in t2]).iteritems()] 100 loops, best of 3: 10.4 ms per loop 不过性能没啥提升了,还是@ipconfiger 的iter版给力了 |