Home >Backend Development >Python Tutorial >Usage of functions map() and reduce() in Python

Usage of functions map() and reduce() in Python

高洛峰
高洛峰Original
2017-03-11 10:06:011976browse

This article mainly introduces the usage of map() function and reduce() function in Python. The code is based on Python2.x version. Friends in need can refer to it

Python has built-in map() and reduce() function.

If you have read Google's famous paper "MapReduce: Simplified Data Processing on Large Clusters", you can roughly understand the concept of map/reduce.

Let’s look at the map first. The map() function receives two parameters, one is a function and the other is a sequence. map applies the passed function to each element of the sequence in turn and returns the result as a new list.

For example, for example, we have a function f(x)=x2, and we want to apply this function to a list [1, 2, 3, 4, 5, 6, 7, 8, 9]. You can use map() to implement it as follows:

2015427113120966.png (341×245)

Now, we use Python code to implement it:

>>> def f(x):
...   return x * x
...
>>> map(f, [1, 2, 3, 4, 5, 6, 7, 8, 9])
[1, 4, 9, 16, 25, 36, 49, 64, 81]

The first parameter passed in by map() is f, which is the function object itself.

You may think that you don’t need the map() function, you can write a loop and calculate the result:

L = []
for n in [1, 2, 3, 4, 5, 6, 7, 8, 9]:
  L.append(f(n))
print L

It is indeed possible, However, from the above loop code, can you understand at a glance "apply f(x) to each element of the list and generate a new list as a result"?

So, map(), as a high-order function, actually abstracts the operation rules. Therefore, we can not only calculate simple f(x)=x2, but also calculate any complex function, such as, Convert all the numbers in this list to strings:

>>> map(str, [1, 2, 3, 4, 5, 6, 7, 8, 9])
['1', '2', '3', '4', '5', '6', '7', '8', '9']

Only one line of code is needed.

Let’s look at the usage of reduce. Reduce applies a function to a sequence [x1, x2, x3...]. This function must receive two parameters. Reduce continues the cumulative calculation of the result with the next element of the sequence. The effect is:

reduce(f, [x1, x2, x3, x4]) = f(f(f(x1, x2), x3), x4)

For example, to sum a sequence, you can use Reduce implementation:

>>> def add(x, y):
...   return x + y
...
>>> reduce(add, [1, 3, 5, 7, 9])
25

Of course, the summation operation can be directly performed using Python’s built-in function sum(), and there is no need to use reduce.

But if you want to transform the sequence [1, 3, 5, 7, 9] into the integer 13579, reduce can come in handy:

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

This example itself is not very useful, but if we consider that the string str is also a sequence, we can slightly change the above example and cooperate with map(), we can write a function to convert str to int:

>>> def fn(x, y):
...   return x * 10 + y
...
>>> def char2num(s):
...   return {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}[s]
...
>>> reduce(fn, map(char2num, '13579'))
13579

The function organized into a str2int is:

def str2int(s):
  def fn(x, y):
    return x * 10 + y
  def char2num(s):
    return {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}[s]
  return reduce(fn, map(char2num, s))

You can also use the lambda function to further Simplified to:

def char2num(s):
  return {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}[s]

def str2int(s):
  return reduce(lambda x,y: x*10+y, map(char2num, s))

That is to say, assuming that Python does not provide the int() function, you are completely You can write your own function to convert a string into an integer, and it only requires a few lines of code!

Exercise

Use the map() function to change the non-standard English name input by the user into a standard name with the first letter in uppercase and other lowercase letters. Input: ['adam', 'LISA', 'barT'], output: ['Adam', 'Lisa', 'Bart'].

The sum() function provided by Python can accept a list and calculate the sum. Please write a prod() function that can accept a list and use reduce() to calculate the product.

The above is the detailed content of Usage of functions map() and reduce() in Python. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn