user6315578
user6315578

Reputation:

Addition of array in python with list in a list

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?

Upvotes: 3

Views: 76

Answers (3)

cs95
cs95

Reputation: 402293

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

Upvotes: 3

MSeifert
MSeifert

Reputation: 152587

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)

Upvotes: 3

juanpa.arrivillaga
juanpa.arrivillaga

Reputation: 95872

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.

Upvotes: 4

Related Questions