我如何计算:
[["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)]