Adding an array in python with a list in a list

How do I summarize the list below?

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

      

I am applying 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 want to get

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

      

Can anyone share some ideas with me?

+3


source to share


3 answers


Are you 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 need to understand that you need to iterate one level deeper, since the return value zip(a,b)

is subscriptions, and if you add sublists, you get concatenation.

+4


source


You tagged it 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 is actually sufficient to convert only one to a NumPy array, but internally NumPy will still convert the other to a NumPy array. It's just less:

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

      

+3


source


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

      

+3


source







All Articles