Python将数字列表与其他数字列表相加

时间:2014-09-03 09:20:23

标签: python list sum add

在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 :(得分:7)

使用zipsumlist comprehension

>>> lists = (listOne, listTwo, listThree)
>>> [sum(values) for values in zip(*lists)]
[10, 9, 16, 11, 13]

答案 1 :(得分:1)

或者,您也可以使用mapzip,如下所示:

>>> map(lambda x: sum(x), zip(listOne, listTwo, listThree))
[10, 9, 16, 11, 13]

答案 2 :(得分: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]