numpy 数组中三个列表的元素加法

qyswt5oh  于 12个月前  发布在  其他
关注(0)|答案(2)|浏览(90)

假设我有这个数组,

arr = [[7, 6], [4, 2, 7],[4,4,6,2]]

我想得到一个新的列表,

list = [15,12,13,2]

我怎么才能得到它?我正在使用以下方法,但它不起作用:

list = np.sum(arr, axis=0)
anauzrmj

anauzrmj1#

可以使用itertools.zip_longest

from itertools import zip_longest

arr = [[7, 6], [4, 2, 7],[4,4,6,2]]

out = list(map(sum, zip_longest(*arr, fillvalue=0)))

输出:[15, 12, 13, 2]

idfiyjo8

idfiyjo82#

另一种可能的解决方案,基于numpy填充(numpy.pad):

a = [[7, 6], [4, 2, 7], [4,4,6,2]]
width = np.max([len(x) for x in a])
np.stack([np.pad(x, (0, width-len(x)), constant_values=0)
         for x in a]).sum(axis=0).tolist()

输出量:

[15, 12, 13, 2]

相关问题