Thanos Smar
Thanos Smar

Reputation: 651

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 .

Upvotes: 1

Views: 579

Answers (2)

Martijn Pieters
Martijn Pieters

Reputation: 1121266

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]]

Upvotes: 3

pschill
pschill

Reputation: 5569

I would define a function that adds two lists, then use a list comprehension to compute your desired result:

def add_lists(a, b):
    return list(x+y for x, y in zip(a, b))

s = list(add_lists(*l) for l in zip(*prefer_indic))

For you example

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]]]

the result will be

[[0, 4.27, 12, 12, 77, 4], [2.01, 3.39, 5, 6, 7, 1]]

Upvotes: 0

Related Questions