## map () function

`map()`Function takes two parameters, a function, a is `Iterable`, `map`to pass successively to the function of each element of the sequence, and the result as a new `Iterator`return.

I.e.  map (f, [x, x, x, x])   then f is a function, [x, x, x, x] is a sequence, then the map operation completed is a sequence in which each element x pass into the function f to execution, the result of each element returned for the execution of a new sequence of the Iterator (inert sequence)

Since Iterator inert sequence, so if you want to display the result in a sequential manner, it is generally preceded list displayed in list form.

Illustration, we have such a function f (x) = x ^ 2 , should this function on a list  `[1, 2, 3, 4, 5, 6, 7, 8, 9]`on, can be used `map()`to achieve the following:

```def f(x):
return x*x
r=map(f,[1,2,3,4,5,6,7,8,9])
list(r)```
``运行结果：[1, 4, 9, 16, 25, 36, 49, 64, 81]``

## reduce function

`reduce`A role in the function of a sequence `[x1, x2, x3, ...]`, the function must receive two parameters, `reduce`the results and continues to the next element in the sequence is calculated as the accumulator.

Effect:`reduce(f, [x1, x2, x3, x4]) = f(f(f(x1, x2), x3), x4)`

For example: the sequence `[1, 3, 5, 7, 9]`into integer`13579`

```from functools Import the reduce
DEF Fn (X, Y):
return X * 10 + Y

the reduce (Fn, [ . 1,. 3,. 5,. 7,. 9 ])

Run Results: 13579```

## lambda functions

lambda line can define a function implemented

lambda arguments: expression function completed

E.g. lambda x, y: x + y and defines a two-argument function summation

## A simplified map / reduce + lambda of

Most start using the map function of the elements of a list of squaring the code can be changed to:

`list(map(lambda x:x*x,[1,2,3,4,5,6,7,8,9]))`

The same result, simplifies the code

Reduce the use of later sequences [1,3,5,7,9] 13579 into an integer code can be simplified to:

```from functools import reduce
reduce(lambda x,y:x*10+y,[1,3,5,7,9])```

Map + lambda structure itself felt fit to frequent use, the future will come in handy.

### Guess you like

Origin www.cnblogs.com/-chenxs/p/11202849.html
Recommended
Ranking
Daily