Python reduce explanation

后端 未结 5 531
广开言路
广开言路 2020-12-20 21:31

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,          


        
相关标签:
5条回答
  • 2020-12-20 21:33

    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.

    0 讨论(0)
  • 2020-12-20 21:39

    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.
    
    0 讨论(0)
  • 2020-12-20 21:46

    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).

    0 讨论(0)
  • 2020-12-20 21:50

    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)
    
    0 讨论(0)
  • 2020-12-20 21:56

    let's trace the reduce

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

    result = result + (5, )

    Notice that your reduction concatenates tuples.

    0 讨论(0)
提交回复
热议问题