问题
In Python is there a simple way of adding the individual numbers of lists to the individual numbers of other lists? In my code I need to add about 10 long lists in a similar fashion to this:
listOne = [1,5,3,2,7]
listTwo = [6,2,4,8,5]
listThree = [3,2,9,1,1]
Therefore I want the result to be:
listSum = [10,9,16,11,13]
Thanks in advance
回答1:
Using zip, sum and list comprehension:
>>> lists = (listOne, listTwo, listThree)
>>> [sum(values) for values in zip(*lists)]
[10, 9, 16, 11, 13]
回答2:
Alternatively, you can also use map
and zip
as follows:
>>> map(lambda x: sum(x), zip(listOne, listTwo, listThree))
[10, 9, 16, 11, 13]
回答3:
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 will have to have the same dimension for this method to work. Otherwise, you will need to pad the arrays with the method described here: https://stackoverflow.com/a/40571482/5060792
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]
来源:https://stackoverflow.com/questions/25640628/python-adding-lists-of-numbers-with-other-lists-of-numbers