This article mainly introduces the usage examples of Pythonmap and reduce functions. This article provides multiple usage examples of the two functions. For more information, see map. The map () function receives two parameters. one is a function, and the other is a sequence. map sequentially applies the input function to each element of the sequence and returns the result as a new list.
For example, if we have a function a (x) = x * 2, we need to apply this function to a list [1, 2, 3, 4, 5, map () can be implemented as follows:
The code is as follows:
>>> Def a (x ):
... Return x * 2
...
>>> Map (a, [1, 2, 3, 4, 5])
[2, 4, 6, 8, 10]
The first parameter a passed in by map is function a. You can also implement this function without the map function:
The code is 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 quantity, map is much simpler. Therefore, map (), as a high-order function, actually abstracts the calculation rules. Therefore, we can not only calculate a (x) = x * 2. you can also compute any complex functions. for example, convert all the numbers in this list into strings:
The code is as follows:
>>> Map (str, [1, 2, 3, 4, 5])
['1', '2', '3', '4', '5']
>>>
You only need a line of code. Let's take a look at the exercises from Gu Xuefeng's python Tutorial: Use the map () function to change the nonstandard English names entered by users into uppercase letters and other standard names in lower case. Input: ['Adam ', 'Lisa', 'Bart'], and output: ['Adam ', 'Lisa', 'Bart']. As an individual, I may first convert all nonstandard English names to lowercase letters, and then use the capitalize () function to convert the first letter to write. the code is as follows:
The code is 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 reduce usage. Reduce (function, sequence, starting_value): calls the function sequentially for items in sequence. if starting_value exists, it can also be called as an initial value. for example, it can be used to sum the List:
The code is 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 directly use the Python built-in function sum (), and there is no need to use reduce. However, to convert the sequence [1, 2, 3, 4, 5, 6, 7] to an integer of 1234567, reduce can be used in the following ways:
The code is as follows:
>>> Def fn (x, y ):
... Return x * 10 + y
...
>>> Reduce (fn, [1, 3, 4, 5, 6, 7])
134567