3

How to sum up the below to list?

a=[[1,2,3],[4,5,6],[7,8,9]]
b=[[1,2,3],[4,5,6],[7,8,9]]

I apply this code:

Total=[x + y for x, y in zip(a, b)]

So the output will be:

Total=[[1,1,2,2,3,3],[4,4,5,5,6,6],[7,7,8,8,9,9]]

but I wish to get

Total=[[2,4,6],[8,10,12],[14,16,18]]

Anyone can share me some ideas?

3 Answers 3

4

You are close:

>>> [[x+y for x,y in zip(sub1, sub2)] for sub1, sub2 in zip(a,b)]
[[2, 4, 6], [8, 10, 12], [14, 16, 18]]

You just have to realize that you need to iterate one level deeper, since the return value of zip(a,b) are sublists, and if you add sublists, you get concatenation.

Sign up to request clarification or add additional context in comments.

Comments

3

You tagged it with NumPy so I'll present the NumPy approach:

import numpy as np
a=[[1,2,3],[4,5,6],[7,8,9]] 
b=[[1,2,3],[4,5,6],[7,8,9]]

np.array(a) + np.array(b)  # this will do element-wise addition
# array([[ 2,  4,  6],
#        [ 8, 10, 12],
#        [14, 16, 18]])

It's actually enough to convert only one to a NumPy array - but internally NumPy will convert the other one to a NumPy array nevertheless. It's just less to type:

np.array(a) + b
a * np.array(b)

Comments

3

How about np.add?

In [326]: import numpy as np

In [327]: np.add(a, b)
Out[327]: 
array([[ 2,  4,  6],
       [ 8, 10, 12],
       [14, 16, 18]])

Comments

Your Answer

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