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

问题描述 投票:1回答:1

在下面的代码中,输出为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将被添加到列表中。我需要添加什么代码才能获得所需的输出?

python-3.x list iteration reduce functools
1个回答
0
投票

您需要其他功能。 itertools.accumulate()生成所有中间结果,functools.reduce()生成以下内容:

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

默认情况下使用加法。或者,您也可以传递任何其他想要的2参数函数:

>>> 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]
© www.soinside.com 2019 - 2024. All rights reserved.