Look at map first. The map () function receives two parameters, one is a function, the other is a sequence, and map passes the incoming function to each element of the sequence sequentially, returning the result as a new list.
For example, we have a function a (x) =x*2, to function in a list [1, 2, 3, 4, 5], you can use map () to achieve the following:
Copy the Code code as follows:
>>> def A (x):
... return x * 2
...
>>> map (A, [1,2,3,4,5])
[2, 4, 6, 8, 10]
Map to the first parameter a, a function, of course you can do without the map function to achieve this function:
Copy the Code code as follows:
>>> list = []
>>> for i in [1, 2, 3, 4, 5]:
... list.append (A (i))
...
>>> Print List
[2, 4, 6, 8, 10]
In terms of code volume, map is much leaner, so map () is a higher-order function, in fact it abstracts the arithmetic rules, so we can not only calculate the simple A (x) =x*2, but also calculate any complex function, for example, the list all the numbers into a string:
Copy the Code code as follows:
>>> map (str,[1,2,3,4,5])
[' 1 ', ' 2 ', ' 3 ', ' 4 ', ' 5 ']
>>>
Only one line of code is needed, and it's done. Let's take a look at the exercises from the Gushe Python tutorial: Use the map () function to change the non-canonical English name entered by the user into the first capitalization and the other lowercase canonical names. Input: [' Adam ', ' Lisa ', ' Bart '], output: [' Adam ', ' Lisa ', ' Bart ']. Personally, I might first convert the non-canonical English name into lowercase and then pass the capitalize () function, converting the first letter to write the code as follows:
Copy the 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 ']
Let's look at the usage of reduce. Reduce (function, sequence, starting_value): Calls the function in the order of the item in the sequence, and if there is a starting_value, it can also be called as an initial value. For example, you can use the sum of a list:
Copy the 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 operation can be built directly into the Python 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 it will come in handy:
Copy the Code code as follows:
>>> def fn (x, y):
... return x * ten + y
...
>>> reduce (FN, [1,3,4,5,6,7])
134567