python - 如何减少列表中的列表

标签 python functools

我的直觉告诉我,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 - 如何减少列表中的列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72847511/

相关文章:

python - 成对距离和残差计算优化

python - 在 Pandas 数据框中水平填充单元格值

python - 给出错误 "the JSON object must be str, not ' 字节'“

python - 如何将 '-'字符串解析到node js本地脚本?

python - Python 中的仿函数与函数闭包

Python - 计算函数通过装饰器的次数

python - matplotlib x 标签放置

python - functools.wraps 有什么作用?

python - 如何将 memory_profiler(python 模块)与类方法一起使用?

python - 从函数内部禁用 `functools.lru_cache`