I. Overview
The reduce operation is one of the most important techniques in functional programming, and its role is to generate a value from the operation of a set. For example, the most common summation, the maximum value, the minimum value, etc. are typical examples of the reduce operation. Python provides a good support for the reduce operation with the built-in reduce function.
function syntax: reduce (function, Iterable[,initializer])
The function parameters have the following meanings:
1. function requires two parameters, one is the result of the save operation, and the other is the element of each iteration.
2, iterable to be iterative processing collection
3, initializer initial value, can not.
The reduce function operates when the reduce method is called:
1, if there is a initializer parameter, the first element value is removed from the iterable, and then the initializer and element values are passed to function processing;
The second element value is then fetched from the iterable, which is passed along with the function's return value to function processing, which iterates through all the elements. The function return value of the last processing is the return value of the reduce function.
2, if the initializer parameter does not exist, the first element value is taken from the iterable as the initializer value, and then the second element and subsequent elements are processed from the iterable. In special cases, if the collection has only one element, reduce returns the value of the first element regardless of how the function is handled.
Let's take a concrete example to illustrate this.
Second, the case
Example 1: Summation
Reduce (lambda re,x:re+x,[2,4,6])
The result is 12. Here we use lambda expression (anonymous function), with two parameters, re refers to the return value after each operation, there is no initializer parameter, the initial value of RE is the first element is 2.
The parameter x is the element that represents the collection.
Reduce (lambda re,x:re+x,[2,4,6],10)
The result is 22. This example passes the initialization parameter 10, so that the function is evaluated starting with the 1th element.
Example 2: Calculating factorial
Reduce (lambda re,x:re*x,range (1,6))
The result is 120. The result of range (1,6) is the list [1,2,3,4,5], which computes the product of these elements.
Third, summary
The reduce function is essentially an iterative operation of each element in the collection by passing in a function and initial value, and the result of each operation is the parameter of the second operation.
And the result of the operation of the last element as the return value of the reduce function.
Python functional Programming: Built-in functions reduce usage notes