The reduce () function accumulates elements in the parameter sequence, and the following article mainly introduces the use of the reduce () function in Python, which is described in detail by the example code, which has a certain reference value for the study or work of everyone. The friends who need to take a look below.
Objective
This article mainly introduces to you about the use of the reduce () function in Python, share it for everyone to reference the study, the following words do not say, come together to see the detailed introduction:
The reduce () function is imported from this library if it is to be used in the library functools. There is a difference between the reduce function and the map function, the map operation is parallel, and the reduce function is the operation of merging multiple parameters, that is, the result of simplifying from multiple conditions, in the computer algorithm, in most cases, it is to simplify. For example, to identify whether the image is a cat, then it is from a number of pixels extracted from a judgment: Yes or No. It could be millions of pixels, just one result. In Google's large-scale cluster, is to use this idea, the previous parallel processing operation called map, parallel processing after the result, it needs to simplify, classify, this simplification and collation of the process is called reduce. Because reduce can only operate on a single host and not be distributed to processing, reduce deals with map results, which means that these results are already very simple and the amount of data is greatly reduced and processed very quickly.
Therefore, the MapReduce process can be called the process of analysis and induction.
Take a look at the following example of reduce ():
#python 3. 6 #蔡军生 #http://blog.csdn.net/caimouse/article/details/51749579 # from Functools import reduce result = reduce ( Lambda x, Y:x+y, [1, 2, 3, 4, 5]) print (result)
Output Result:
15
In this case, the calculation process is actually the following:
(((((1+2) +3) +4) +5)
Let's look at a factorial example:
#python 3. 6 #蔡军生 #http://blog.csdn.net/caimouse/article/details/51749579 # from Functools import reduce n = 3 print (Reduce ( Lambda x, y:x * y, Range (1, n + 1)) # 6
Output Result:
6
Reduce function, the reduce function accumulates elements in the parameter sequence.
Definition of the Reduce function:
Reduce (function, sequence[, initial]), value
The function parameter is a two-parameter, and reduce sequentially takes an element from sequence and invokes function again with the result of the last call to function.
The first call to function, if supplied with the initial parameter, calls function with the first element in sequence and initial as a parameter, otherwise the function is called with the first two elements in the sequence sequence.
Reduce (lambda x, y:x + y, [2, 3, 4, 5, 6], 1)
The result is 21 ((((((((((((1+2) +3) +4) +5) +6))
Reduce (lambda x, y:x + y, [2, 3, 4, 5, 6])
Result is 20
Summarize