Reputation: 1995
I checked similar problem at sum of N lists element-wise python
but mine is a little bit more complicate cause I am adding list of list with another list of list
my list looks like it below
[[0 0.014285714 0.035600016]
,[0.014285714 0 0.038359389]
,[0.035600016 0.038359389 0]]
[[0 0.014285714 0.035600016]
,[0.014285714 0 0.038359389]
,[0.035600016 0.038359389 0]]
so adding these two then results has 3 by 3 matrix
how could I efficiently add these two lists?
Upvotes: 2
Views: 375
Reputation: 331
Here is a recursive solution using 'vanilla' python and recursion (This solution works for nested tuples or lists)
from operator import add
def list_recur(l1, l2, op = operator.add):
if not l1:
return type(l1)([])
elif isinstance(l1[0], type(l1)):
return type(l1)([list_recur(l1[0], l2[0], op)]) + \
list_recur(l1[1:],l2[1:], op)
else:
return type(l1)([op(l1[0], l2[0])]) + \
list_recur(l1[1:], l2[1:], op)
This solution takes arguments list1, list2 and optionally the operation you want to perform element-wise
(by default addition).
For example, list_recur([ [1, 2, 3, [4, 5] ], [1, 2, 3, [4, 5] ])
will return [ [2, 4, 6, [8, 10] ]
.
More complex examples will work too:
list_recur([[[[[1,[[[[2, 3]]]]]]]], [[[[3, [[[[4, 1]]]]]]]], lambda x, y: \
x < y)
will return [[[[True, [[[[True, False]]]]]]]]
`
Upvotes: 2
Reputation: 16930
Can i solve using numpy:
>>> a = [[1, 2, 3], [1, 2, 3], [1, 2, 3]]
>>> b = [[4, 5, 6], [4, 5, 6], [4, 5, 6]]
>>> from numpy import array, sum
>>> list(array(a) + array(b))
[array([5, 7, 9]), array([5, 7, 9]), array([5, 7, 9])]
OR
>>> sum([a, b], axis=0)
array([[5, 7, 9],
[5, 7, 9],
[5, 7, 9]])
>>>
Upvotes: 3
Reputation: 32189
If you are working with numpy matrices, @AlexThornton has the best answer
If you are dealing with lists, you should do:
summed_list = [[c+d for c,d in zip(i,j)] for i,j in zip(a,b)] #a,b are your two lists
>>> a = [[1,2,3],[1,2,3],[1,2,3]]
>>> b = [[4,5,6],[4,5,6],[4,5,6]]
>>> summed_list = [[c+d for c,d in zip(i,j)] for i,j in zip(a,b)] #a,b are your two lists
>>> print summed_list
[[5,7,9],
[5,7,9],
[5,7,9]]
Upvotes: 3
Reputation: 20351
You tagged your question numpy
, so I assume this is OK:
import numpy as np
a = np.matrix(a)
b = np.matrix(b)
c = a + b
Where a
and b
are your two lists, and c
is the two added together.
By far the simplest with numpy
. :)
Upvotes: 3