Python reduce explanation

后端 未结 5 623
广开言路
广开言路 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.

提交回复
热议问题