Look at map first.map()
The function receives two parameters, one is a function and the other isIterable
,map
Functions the passed-in function sequentially to each element of the sequence and takes the result as a newIterator
Return.For example, we have a function f (x) =x2, to function on a list [1, 2, 3, 4, 5, 6, 7, 8, 9]
, it can be map()
implemented as follows:
f(x) = x * x │ │ ┌────────────--------───┐ │ │ │ │ │ │ │ │ │ ▼ ▼ ▼ ▼ ▼ ▼ ▼ ▼ ▼[ 1 2 3 4 5 6 7 8 9 ] │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ ▼ ▼ ▼ ▼ ▼ ▼ ▼ ▼ ▼[ 1 4 9 16 25 36 49 64 81 ]
Now, we use Python code to implement:
1 def f (x): 2 ... return x * x3 ... 4 >>> r = map (f, [1, 2, 3, 4, 5, 6, 7, 8, 9])5 >>> list (r)
6 [1, 4, 9, 16, 25, 36, 49, 64, 81]
map()
The first parameter passed in is the f
function object itself. Since the result r
is one Iterator
, it is an Iterator
inert sequence, so the list()
function allows it to calculate the entire sequence and return a list.
Look againreduce
The usage.reduce
A function that acts on a sequence[x1, x2, x3, ...]
, this function must receive two parameters,reduce
The result continues and the next element of the sequence is accumulated, and the effect is:
reduce(f, [x1, x2, x3, x4]) = f(f(f(x1, x2), x3), x4)
For example, to sum a sequence, it can be implemented with reduce:
from Import Reduce def Add (x, y): ... return x + y ... >>> reduce (add, [1, 3, 5, 7, 9])25
This example is not very useful in itself, but if we consider that the string str
is also a sequence, with a slight change to the above example, map()
we can write the str
converted int
function:
>>> fromFunctoolsImportReduce>>>deffn (x, y): ...returnX * 10 +y ...>>>defChar2num (s): ... digits= {'0': 0,'1': 1,'2': 2,'3': 3,'4': 4,'5': 5,'6': 6,'7': 7,'8': 8,'9'8 {}... returnDigits[s] ...>>> reduce (FN, map (Char2num,'13579'))13579