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

问题描述 投票:3回答:3

在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]

提前致谢

python list sum add
3个回答
7
投票

使用zipsumlist comprehension

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

1
投票

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

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

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]
© www.soinside.com 2019 - 2024. All rights reserved.