5

Looking for a pythonic way to sum values from multiple lists: I have got the following list of lists:

a = [0,5,2]
b = [2,1,1]
c = [1,1,1]
d = [5,3,4]
my_list = [a,b,c,d]

I am looking for the output:

[8,10,8]

I`ve used:

print ([sum(x) for x in zip(*my_list )])

but zip only works when I have 2 elements in my_list. Any idea?

1
  • zip works for any number of elements. Commented Oct 8, 2018 at 13:34

3 Answers 3

6

zip works for an arbitrary number of iterables:

>>> list(map(sum, zip(*my_list)))
[8, 10, 8]

which is, of course, roughly equivalent to your comprehension which also works:

>>> [sum(x) for x in zip(*my_list)]
[8, 10, 8]
Sign up to request clarification or add additional context in comments.

Comments

0

Numpy has a nice way of doing this, it is also able to handle very large arrays. First we create the my_list as a numpy array as such:

import numpy as np
a = [0,5,2]
b = [2,1,1]
c = [1,1,1]
d = [5,3,4]
my_list = np.array([a,b,c,d])

To get the sum over the columns, you can do the following

np.sum(my_list, axis=0)

Alternatively, the sum over the rows can be retrieved by

np.sum(my_list, axis=1)

Comments

0

I'd make it a numpy array and then sum along axis 0:

my_list = numpy.array([a,b,c,d])    
my_list.sum(axis=0)

Output:

[ 8 10  8]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.