Reputation: 425
In the below code, the output is 38
, and i want a separate list with the output [34,36,38]
.
from functools import *
nums = [0, 34, 2, 2]
sum_num = reduce(lambda a, b : a+b, nums)
As the reduce function adds 0
and 34
, i need to append this value in a separate list, now in the second iteration i need to get 34 + 2
appended to the list. and at last 38
will be appended to the list.
what piece of code do i need to add to get the desired output?
Upvotes: 3
Views: 724
Reputation: 2711
According to the docs, the reduce
function is roughly equivalent to:
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
So, to get each sum as we move through the process, we can use the function:
def reduce(function, iterable):
it = iter(iterable)
value = next(it)
values = []
for element in it:
value = function(value, element)
values.append(value)
return values
(Simplified since the initializer
parameter is not used)
Upvotes: 0
Reputation: 70592
You need a different function. itertools.accumulate()
generates all the intermediate results functools.reduce()
produces under the covers:
>>> from itertools import accumulate
>>> nums = [0, 34, 2, 2]
>>> list(accumulate(nums))
[0, 34, 36, 38]
It uses addition by default. Or you can pass whatever other 2-argument function you want instead:
>>> 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]
If you don't want the 0 at the start, you'll have to get rid of that yourself; e.g.,
>>> f = accumulate(nums)
>>> next(f) # throw out first result
0
>>> list(f) # and make a list out of what remains
[34, 36, 38]
Upvotes: 6