Look at the map first. The map () function receives two parameters, one is a function, the other is a sequence, and map functions the passed-in function to each element of the sequence and returns the result as a new list.
For example, for example, we have a function a (x) =x*2, which functions on a list [1, 2, 3, 4, 5], you can use map () to achieve the following:
Copy Code code as follows:
>>> def A (x):
... return x * 2
...
>>> map (A, [1,2,3,4,5])
[2, 4, 6, 8, 10]
The first parameter A, the A function, that is passed in the map, of course, can be implemented without the map function:
Copy Code code as follows:
>>> list = []
>>> for i in [1, 2, 3, 4, 5]:
... list.append (A (i))
...
>>> Print List
[2, 4, 6, 8, 10]
As far as the code is concerned, the map is a lot leaner, so the map () as a high-order function, in fact, abstracts the rules of operation, so that we can compute a simple a (x) =x*2 and compute any complex functions, such as converting all the numbers into strings:
Copy Code code as follows:
>>> map (str,[1,2,3,4,5])
[' 1 ', ' 2 ', ' 3 ', ' 4 ', ' 5 ']
>>>
Just one line of code, it's done. Let's look again at the exercises from the Gushe Python tutorial: Use the map () function to change the nonstandard English name entered by the user into the first letter capital and other lowercase canonical names. Input: [' Adam ', ' Lisa ', ' Bart '], output: [' Adam ', ' Lisa ', ' Bart ']. As for me, I may first convert the nonstandard English name to lowercase and then through the capitalize () function, convert the first letter to write, the code is as follows:
Copy Code code as follows:
>>> def caps (name):
... return name.capitalize ()
...
>>> def lowers (name):
... return name.lower ()
...
>>> Map (Caps, map (lowers,[' Adam ', ' LISA ', ' BarT '))
[' Adam ', ' Lisa ', ' Bart ']
See the use of reduce again. Reduce (function, sequence, starting_value): Iterates the call function on the item order in sequence, and if there is a starting_value, it can also be invoked as an initial value. For example, you can use to sum the list:
Copy Code code as follows:
>>> def add (x, y):
... return x + y
...
>>> reduce (add, [1, 3, 5, 7, 9])
25
>>> reduce (Add, range (1, 11))
55
>>> reduce (Add, range (1, 11), 20)
75
Of course the sum can be used directly with the Python built-in function sum (), no need to use reduce. But if you want to transform the sequence [1,2,3,4,5,6,7] into an integer 1234567,reduce you can come in handy:
Copy Code code as follows:
>>> def fn (x, y):
... return x * + y
...
>>> reduce (FN, [1,3,4,5,6,7])
134567