I'm relatively new to Python and am having trouble
with Folds or more specifically, reduce()'s 'initializer' argument

e.g. reduce(function, iterable[, initializer])

Here is the function...

>>> def x100y(x,y):
...     return x*100+y

Could someone explain why reduce() produces 44...

>>> reduce(x100y, (), 44)
44

or why it produces 30102 here...

>>> reduce(x100y, [1,2], 3)
30102
有帮助吗?

解决方案

From the docs:

reduce(function, iterable[, initializer])

Apply function of two arguments cumulatively to the items of iterable, from left to right, so as to reduce the iterable to a single value. For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates ((((1+2)+3)+4)+5). The left argument, x, is the accumulated value and the right argument, y, is the update value from the iterable. If the optional initializer is present, it is placed before the items of the iterable in the calculation, and serves as a default when the iterable is empty. If initializer is not given and iterable contains only one item, the first item is returned.

The initializer is placed as element 0 in your iterable and if there are no elements in your iterable it is returned. (So this is why you get 44)

Also, x100y is not a valid python function. If you want to make it into a valid python function you would have to do

reduce(lambda x,y: x*100*y,[1,2],3)

which is equivalent to

(3*100*1)*100*2 which should give 60000 (why you got the value you had is probably because of an error)

Documentation on lambda is here

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top