在下面的代码中,输出是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
将被追加到列表中。我需要添加什么代码才能获得所需的输出?
发布于 2020-02-12 18:44:28
您需要一个不同的函数。itertools.accumulate()
生成functools.reduce()
在幕后生成的所有中间结果:
>>> from itertools import accumulate
>>> nums = [0, 34, 2, 2]
>>> list(accumulate(nums))
[0, 34, 36, 38]
默认使用加法。或者你可以传递任何你想要的其他双参数函数:
>>> 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]
发布于 2020-02-12 18:45:53
根据the docs的说法,reduce
函数大致相当于:
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
参数,因此得到简化)
https://stackoverflow.com/questions/60194925
复制