Thanos Smar Thanos Smar - 3 months ago 9
Python Question

How to find sum of list of lists using for-loop

prefer_indic = [[[0, 4, 6, 5, 45, 1], [2, 3, 5, 6, 7, 1]],[[0, 0.27, 6, 7, 32, 3], [0.01, 0.39, 0, 0, 0, 0]]]


I want to create a sum list that will add every value from every list of lists with each corresponding ones.
To be accurate i want:

sum = [[0+0, 4+0.27, 6+6, 5+7, 45+32, 1+3], [2+0.1, 3+0.39, 5+0, 6+0, 7+0, 1+0]]


I want to do it with a for loop so that i can use the same algorithm for bigger list of lists.I made the example simple to make it more readable. I have python 2.7 .

Answer

Use the zip() function to pair up elements from 2 or more lists, then use sum() to add up the combined values:

summed = [[sum(zipped) for zipped in zip(*column)] for column in zip(*prefer_indic)]

Note the zip(*prefer_indic) call, which transposes your matrix so that you pair up the 'columns' of your nested lists, not the rows.

If your lists are larger, it may be beneficial to using the iterative version of zip; use the future_builtins.zip() location and your code is automatically forward-compatible with Python 3:

try:
    from future_builtins import zip
except ImportError:
    # Python 3

summed = [[sum(zipped) for zipped in zip(*column)] for column in zip(*prefer_indic)]

Demo:

>>> from future_builtins import zip
>>> prefer_indic = [[[0, 4, 6, 5, 45, 1], [2, 3, 5, 6, 7, 1]],[[0, 0.27, 6, 7, 32, 3], [0.01, 0.39, 0, 0, 0, 0]]]
>>> [[sum(zipped) for zipped in zip(*column)] for column in zip(*prefer_indic)]
[[0, 4.27, 12, 12, 77, 4], [2.01, 3.39, 5, 6, 7, 1]]