如何将 reduce 函数的每次迭代存储在列表中?

How can i store each iteration of a reduce function in a list?

在下面的代码中,输出是 38,我想要一个包含输出 [34,36,38].

的单独列表
from functools import *
nums = [0, 34, 2, 2]
sum_num = reduce(lambda a, b : a+b, nums)

由于 reduce 函数添加了 034,我需要将这个值附加到一个单独的列表中,现在在第二次迭代中我需要将 34 + 2 附加到列表。最后 38 将附加到列表中。 我需要添加什么代码才能获得所需的输出?

您需要一个不同的功能。 itertools.accumulate() 生成所有中间结果 functools.reduce() 在幕后生成:

>>> from itertools import accumulate
>>> nums = [0, 34, 2, 2]
>>> list(accumulate(nums))
[0, 34, 36, 38]

默认使用加法。或者你可以传递你想要的任何其他 2-argument 函数:

>>> list(accumulate(nums, lambda a, b: a + b)) # same as the default
[0, 34, 36, 38]
>>> list(accumulate(nums, lambda a, b: a + 2*b))
[0, 68, 72, 76]

如果您不想要开头的 0,则必须自己删除它;例如,

>>> f = accumulate(nums)
>>> next(f)  # throw out first result
0
>>> list(f)  # and make a list out of what remains
[34, 36, 38]

根据the docsreduce函数大致等同于:

def reduce(function, iterable, initializer=None):
    it = iter(iterable)
    if initializer is None:
        value = next(it)
    else:
        value = initializer
    for element in it:
        value = function(value, element)
    return value

所以,为了在我们完成这个过程的过程中获得每笔总和,我们可以使用函数:

def reduce(function, iterable):
    it = iter(iterable)
    value = next(it)
    values = []
    for element in it:
        value = function(value, element)
        values.append(value)
    return values

(由于未使用 initializer 参数而简化)