如果数组行具有不同的长度,则对数组列求和

Ser*_*ado -1 python arrays sum list python-2.7

我想知道如果行具有不同的长度,是否可以对数组的列求和.

这是我要总结的数组:

input_val = [[1, 2, 3, 5],
             [1, 2, 3],
             [1, 2, 3, 4, 5]]
Run Code Online (Sandbox Code Playgroud)

这将是结果:

output_val = [3, 6, 9, 9, 5]
Run Code Online (Sandbox Code Playgroud)

我想到了为行添加零的可能性:

input_val = [[1, 2, 3, 5, 0],
             [1, 2, 3, 0, 0],
             [1, 2, 3, 4, 5]]
Run Code Online (Sandbox Code Playgroud)

然后总结列,但也许有更好的方法来做到这一点?

MSe*_*ert 6

您可以使用itertools.zip_longest以下方法轻松地执行零填充:

>>> import itertools
>>> list(map(sum, itertools.zip_longest(*input_val, fillvalue=0)))
[3, 6, 9, 9, 5]
Run Code Online (Sandbox Code Playgroud)

在python-2.x上,函数有一个不同的名称itertools.izip_longest,你不需要list强制转换:

>>> import itertools
>>> map(sum, itertools.izip_longest(*input_val, fillvalue=0))
[3, 6, 9, 9, 5]
Run Code Online (Sandbox Code Playgroud)

  • @SergieManchado在python 2.7`zip_longest()`中命名为`izip_longest()` (3认同)