2015-07-20 69 views
4
start = [(1,2),(3,4),(1,3),(3,5)] 

如何在x值相同的情况下有效地添加元组y值(我正在使用700,000个元组)?如果x值相同,如何添加元组的y值?

end = [(1,5),(3,9)] 

我试图:

我想我的元组的列表转换为个人词典列表。但是,这看起来并不是我最有效的方法。

然而,我不知道如何将我的元组列表转换为单个字典的列表。

我试图字典(开始),这:

a = [] 
for lv in length_view: 
    a.append(dict(lv)) 

我去要不然怎么样?

然后我会尝试使用:

from collections import Counter 
c = Counter() 
for some_dictionary in some_list: 
    c.update(some_dictionary) 

[{key: value} for key, value in c.items()] 

回答

2

我能想到的方法,使用collections.defaultdict是 -

>>> from collections import defaultdict 
>>> dic = defaultdict(int) 
>>> for a, b in start: 
...  dic[a] += b 
... 
>>> list(dic.items()) 
[(1, 5), (3, 9)] 

如果您正在使用Python 2.x中,你不需要list(..)周围dic.items(),如.items()返回在Python 2.x的列表

1

使用defaultdict功能从收集模块。

from collections import defaultdict 
start = [(1,2),(3,4),(1,3),(3,5)] 
d = defaultdict(list) 
for x,y in start: 
    d[x].append(y) 

print [(i,sum(j)) for i,j in d.items()] 
+1

当你结束了为什么使用列表作为defaultdict容器总结数值呢? – poke

+1

戳,后来我意识到。 –

+0

哈哈,好的:D:D – poke

1

您可以使用dict.setdefault方法来创建独特的键和值的有关名单中,一本字典,然后遍历其项目和计算值sum

>>> start = [(1,2),(3,4),(1,3),(3,5)] 
>>> d={} 
>>> for i,j in start: 
... d.setdefault(i,[]).append(j) 
... 

>>> [(i,sum(j)) for i,j in d.items()] 
[(1, 5), (3, 9)] 

但作为更有效的方式使用collections.defaultdict

>>> from collections import defaultdict 
>>> d = defaultdict(int) 
>>> for i,j in start: 
...  d[i]+=j 
... 
>>> d.items() 
[(1, 5), (3, 9)] 
相关问题