2013-07-09 123 views
2

多維列表我怎麼能計算這個:總和蟒蛇

[["toto", 3], ["titi", 10], ["toto", 2]] 

得到這個:

[["toto", 5], ["titi", 10]] 

感謝

回答

4

您可以使用collections.defaultdict

>>> from collections import defaultdict 
>>> d = defaultdict(list) 
>>> for i, j in L: 
...  d[i].append(j) 
... 
>>> [[i, sum(j)] for i, j in d.items()] 
[['titi', 10], ['toto', 5]] 

感謝@raymonad的替代,清潔,解決方法:

>>> d = defaultdict(int) 
>>> L = [["toto", 3], ["titi", 10], ["toto", 2]] 
>>> for i, j in L: 
...  d[i] += j 
... 
>>> d.items() 
[('titi', 10), ('toto', 5)] 
+2

或者乾脆'defaultdict (int)'在循環中用'd [i] + = j'。 – raymonad

+0

@raymonad是不是python真棒? – TerryA

3

您可以使用itertools.groupby到組的第一個項目,然後計算總和:

In [1]: data = [["toto", 3], ["titi", 10], ["toto", 2]] 

In [2]: from itertools import groupby 

In [3]: from operator import itemgetter 

In [4]: key = itemgetter(0) 

In [5]: [[k, sum(l[1] for l in g)] 
    ..: for k, g in groupby(sorted(data, key=key), key=key)] 
Out[5]: [['titi', 10], ['toto', 5]] 
0
l1=[["toto", 3], ["titi", 10], ["toto", 2]] 
d={} 
for i in range(len(l1)): 
    try: 
     d[l1[i][0]]+=l1[i][1] 
    except KeyError: 
     d[l1[i][0]]=l1[i][1] 
l2=[] 
for k,v in d.items(): 
    l2.append([k,v])