Common functions python 2

2, reduce () function

reduce () function is also built-in python a higher-order function. reduce function received parameters () and map () is similar to a function f, a list, but the behavior and map () different, reduce () function f must receive the incoming two parameters, reduce () for each of the list repeatedly calling the function f elements, and returns the final result value.

For example, a write function, receiving x, y, returns the x, y and hair:

def f(x,y)

  return x+y

When calling reduce (f, [2,6,9]), reduce the function is calculated as follows:

First calculate the first two elements: f (2,6), the result is 4;

The results of the three elements and then calculates: f (4,9), the result is 13;

 

When the above calculation is actually summing all elements of the list. Although the python built-sum function sum (), however, the use of reduce () is also very simple summation

 

reduce () may also receive a third optional parameter, calculated as the initial value. If the initial value is 100. Calculated:

reduce(f,[2,6,9],100)

Results becomes 113, as the first round of calculation:

And calculating the initial value of the first element: f (100,1), the result is 101.

 

python built-sum function sun (), but no sum function, please use reduce () to Quadrature:

Input: [2,4,5,7,12]

Output: Results 2 * 4 * 7 * 12

 

reduce () function f receiving two arguments, and returns a result, in order to continue the next round of calculation

as follows:

 

Guess you like

Origin www.cnblogs.com/czb4256/p/11141226.html