Python 使用其他数字列表相加的数字列表
在Python中,有没有简单的方法可以把一个列表里的每个数字加到另一个列表里的对应数字上?在我的代码中,我需要以类似的方式把大约10个长列表相加,像这样:
listOne = [1,5,3,2,7]
listTwo = [6,2,4,8,5]
listThree = [3,2,9,1,1]
所以我想要的结果是:
listSum = [10,9,16,11,13]
提前谢谢你们!
3 个回答
0
使用numpy进行向量化操作是另一种选择。
>>> import numpy as np
>>> (np.array(listOne) + np.array(listTwo) + np.array(listThree)).tolist()
[10, 9, 16, 11, 13]
或者对于多个列表,可以更简洁地写:
>>> lists = (listOne, listTwo, listThree)
>>> np.sum([np.array(l) for l in lists], axis=0).tolist()
[10, 9, 16, 11, 13]
注意:每个列表必须具有相同的维度,这种方法才能正常工作。否则,你需要用这里描述的方法来填充数组:https://stackoverflow.com/a/40571482/5060792
为了完整性:
>>> 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]
1
另外,你也可以使用 map
和 zip
,方法如下:
>>> map(lambda x: sum(x), zip(listOne, listTwo, listThree))
[10, 9, 16, 11, 13]