我该如何计算:
[["toto", 3], ["titi", 10], ["toto", 2]]
得到这个:
[["toto", 5], ["titi", 10]]
谢谢
我该如何计算:
[["toto", 3], ["titi", 10], ["toto", 2]]
得到这个:
[["toto", 5], ["titi", 10]]
谢谢
>>> 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)]
您可以使用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]]
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])