在下面的代码中,输出为38
,我想要一个单独的列表,并带有输出[34,36,38]
。
from functools import *
nums = [0, 34, 2, 2]
sum_num = reduce(lambda a, b : a+b, nums)
当reduce函数将0
和34
相加时,我需要将此值附加到单独的列表中,现在在第二次迭代中,我需要将34 + 2
附加到列表中。最后38
将被添加到列表中。我需要添加什么代码才能获得所需的输出?
您需要其他功能。 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]