Tuesday, October 1, 2013

Sum a multidimensional list in python

How can i compute this :

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

to obtain this:

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

thanks

You can use 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]]

Thanks @raymonad for the alternate, cleaner, solution:

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

No comments:

Post a Comment