2

我该如何计算:

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

得到这个:

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

谢谢

4

3 回答 3

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)]
于 2013-07-09T11:09:12.937 回答
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]]
于 2013-07-09T11:11:44.733 回答
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])
于 2013-07-09T11:17:01.943 回答