Python map and reduce function usage examples

  • 2020-04-02 14:35:26
  • OfStack

Look at the map. The map() function takes two arguments, a function and a sequence, and the map applies the incoming function to each element of the sequence in turn, returning the result as a new list.

For example, if we have a function a(x)=x*2, to apply this function on a list [1, 2, 3, 4, 5], we can use map() to achieve the following:


>>> def a(x):
...     return x * 2
...
>>> map(a, [1,2,3,4,5])
[2, 4, 6, 8, 10]

Map passes in the first parameter a, which is the function a. Of course, you can also implement this function without the map function:


>>> list = []
>>> for i in [1, 2, 3, 4, 5]:
...     list.append(a(i))
...
>>> print list
[2, 4, 6, 8, 10]

In terms of the amount of code, map is much more compact, so as a higher-order function, map() actually abstracts the operation rules. Therefore, we can not only calculate the simple a(x)=x * 2, but also calculate any complex function, such as turning all the Numbers in the list into strings:


>>> map(str,[1,2,3,4,5])
['1', '2', '3', '4', '5']
>>>

All it takes is one line of code. Let's look again at the problem set from gu xuefeng's python tutorial: using the map () function, change the non-standard English name entered by the user into an uppercase and other lowercase standard name. Input: [' Adam ', 'LISA', 'barT'], output: [' Adam 'and' LISA ', 'barT']. Personally, I would probably convert all non-canonical English names to lowercase and then use the capitalize() function to convert the first letter to write. 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']

Now let's look at the use of reduce. Reduce (function, sequence, starting_value) : function is called over the order of items in the sequence. If there is starting_value, it can also be called as an initial value. For example, it can be used to sum a List:


>>> 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, summation can be done directly using the Python built-in function sum(), without reducing. But if you want to convert the sequence [1,2,3,4,5,6,7] to the integer 1234567, reduce comes in handy:


>>> def fn(x, y):
...     return x * 10 + y
...
>>> reduce(fn, [1,3,4,5,6,7])
134567


Related articles: