Python add lists of numbers with other lists of numbers
In Python, is there an easy way to add separate list numbers to separate numbers of other lists? In my code, I need to add about 10 long lists, similar to this:
listOne = [1,5,3,2,7]
listTwo = [6,2,4,8,5]
listThree = [3,2,9,1,1]
So I want the result to be:
listSum = [10,9,16,11,13]
Thank you in advance
+3
source to share
3 answers
Using numpy for vectorized operations is another option.
>>> import numpy as np
>>> (np.array(listOne) + np.array(listTwo) + np.array(listThree)).tolist()
[10, 9, 16, 11, 13]
Or more succinctly for many lists:
>>> lists = (listOne, listTwo, listThree)
>>> np.sum([np.array(l) for l in lists], axis=0).tolist()
[10, 9, 16, 11, 13]
Note. Each list must have the same dimension for this method to work. Otherwise, you will need to fill the arrays in the way described here: fooobar.com/questions/721776 / ...
For completeness:
>>> listOne = [1,5,3,2,7]
>>> listTwo = [6,2,4,8,5]
>>> listThree = [3,2,9,1,1]
>>> listFour = [2,4,6,8,10,12,14]
>>> listFive = [1,3,5]
>>> l = [listOne, listTwo, listThree, listFour, listFive]
>>> def boolean_indexing(v, fillval=np.nan):
... lens = np.array([len(item) for item in v])
... mask = lens[:,None] > np.arange(lens.max())
... out = np.full(mask.shape,fillval)
... out[mask] = np.concatenate(v)
... return out
>>> boolean_indexing(l,0)
array([[ 1, 5, 3, 2, 7, 0, 0],
[ 6, 2, 4, 8, 5, 0, 0],
[ 3, 2, 9, 1, 1, 0, 0],
[ 2, 4, 6, 8, 10, 12, 14],
[ 1, 3, 5, 0, 0, 0, 0]])
>>> [x.tolist() for x in boolean_indexing(l,0)]
[[1, 5, 3, 2, 7, 0, 0],
[6, 2, 4, 8, 5, 0, 0],
[3, 2, 9, 1, 1, 0, 0],
[2, 4, 6, 8, 10, 12, 14],
[1, 3, 5, 0, 0, 0, 0]]
>>> np.sum(boolean_indexing(l,0), axis=0).tolist()
[13, 16, 27, 19, 23, 12, 14]
0
source to share