Python reduce explanation

拜拜、爱过 提交于 2019-11-28 08:21:13

问题


I'm not able to understand the following code segment:

>>> lot = ((1, 2), (3, 4), (5,))
>>> reduce(lambda t1, t2: t1 + t2, lot)
(1, 2, 3, 4, 5)

How does the reduce function produce a tuple of (1,2,3,4,5) ?


回答1:


It's easier if you break out the lambda into a function, so it's clearer to what's going on:

>>> def do_and_print(t1, t2):
    print 't1 is', t1
    print 't2 is', t2
    return t1+t2

>>> reduce(do_and_print, ((1,2), (3,4), (5,)))
t1 is (1, 2)
t2 is (3, 4)
t1 is (1, 2, 3, 4)
t2 is (5,)
(1, 2, 3, 4, 5)



回答2:


reduce() applies a function sequentially, chaining the elements of a sequence:

reduce(f, [a,b,c,d], s)

is the same as

f(f(f(f(s, a), b), c), d)

and so on. In your case the f() is a lambda function (lambda t1, t2: t1 + t2) which just adds up its two arguments, so you end up with

(((s + a) + b) + c) + d

and because the parenthesizing on adding sequences doesn't make any difference, this is

s + a + b + c + d

or with your actual values

(1, 2) + (3, 4) + (5,)

If s is not given, the first term is just not done, but usually the neutral element is used for s, so in your case () would have been correct:

reduce(lambda t1, t2: t1 + t2, lot, ())

But without it, you only run into trouble if lot has no elements (TypeError: reduce() of empty sequence with no initial value).




回答3:


reduce(...) reduce(function, sequence[, initial]) -> value

Apply a function of two arguments cumulatively to the items of a sequence,
from left to right, so as to reduce the sequence to a single value.
For example, reduce(lambda x, y: x+y, ((1, 2), (3, 4), (5))) calculates
(((1+2)+(3+4))+5).  If initial is present, it is placed before the items
of the sequence in the calculation, and serves as a default when the
sequence is empty.



回答4:


let's trace the reduce

result = (1,2) + (3,4)

result = result + (5, )

Notice that your reduction concatenates tuples.




回答5:


reduce takes a function and an iterator as arguments. The function must accept two arguments.

What reduce does is that it iterates through the iterator. First it sends the first two values to the function. Then it sends the result of that together with the next value, and so on.

So in your case, it takes the first and the second item in the tuple, (1,2) and (3,4) and sends them to the lambda function. That function adds them together. The result is sent to the lambda function again, together with the third item. Since there are no more items in the tuple, the result is returned.



来源:https://stackoverflow.com/questions/13603361/python-reduce-explanation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!