我的直觉告诉我reduce(来自functools import reduce)将提供我想要的东西,但我不能在这里用它.

def test_reduce_lists_by_summing_them():
    """
    Sum each item from the first list with the same positional item from the subsequent list. 
    The result is the next first list and appended to the returned result list.
    """
    input_ = [[1, 0, 0], [0, 1, 0], [0, 0, 2], [3, 0, 0]]
    expected_output = [[1, 1, 0], [1, 1, 2], [4, 1, 2]]

    def f(x, y):
        """Return the sum of two positional items"""
        return x + y

    output = []
    for group in zip(input_[0:], input_[1:]):
        # Obvisously not working since the first list is not generated but just taken grp[0]
        output.append(list(map(f, group[0], group[1])))
    assert output == expected_output

推荐答案

你要找的是accumulate:

from itertools import accumulate

# perhaps, convert it to a list explicitly
accumulate(input_, lambda x, y: list(map(sum, zip(x, y))))

# a more explicit equivalent:
list(accumulate(input_, lambda x, y: [x_+y_ for x_, y_ in zip(x, y)]))

如果你愿意使用numpy,它将非常简单:

np.array(input_).cumsum(axis=0)

UPD演示:

In [36]: list(accumulate(input_, lambda x, y: list(map(sum, zip(x, y)))))
Out[36]: [[1, 0, 0], [1, 1, 0], [1, 1, 2], [4, 1, 2]]

In [37]: list(accumulate(input_, lambda x, y: [x_+y_ for x_, y_ in zip(x, y)]))
Out[37]: [[1, 0, 0], [1, 1, 0], [1, 1, 2], [4, 1, 2]]

In [38]: np.array(input_).cumsum(axis=0)
Out[38]: 
array([[1, 0, 0],
       [1, 1, 0],
       [1, 1, 2],
       [4, 1, 2]])

Python相关问答推荐

连接两个具有不同标题的收件箱

使可滚动框架在tkinter环境中看起来自然

图像 pyramid .难以创建所需的合成图像

如何从.cgi网站刮一张表到rame?

在Mac上安装ipython

如何在Python数据框架中加速序列的符号化

如何在Raspberry Pi上检测USB并使用Python访问它?

如果条件不满足,我如何获得掩码的第一个索引并获得None?

Plotly Dash Creating Interactive Graph下拉列表

在两极中过滤

如何在TensorFlow中分类多个类

lityter不让我输入左边的方括号,'

跳过嵌套JSON中的级别并转换为Pandas Rame

交替字符串位置的正则表达式

如何在GEKKO中使用复共轭物

如何使用matplotlib查看并列直方图

获取git修订版中每个文件的最后修改时间的最有效方法是什么?

Django抛出重复的键值违反唯一约束错误

EST格式的Azure数据库笔记本中的当前时间戳

将索引表转换为Numy数组