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

Source: Internet
Author: User
This article mainly introduces the usage of map () and reduce () functions in Python. the code is based on Python2.x. if you need it, refer to the Python built-in map () and reduce () functions () function.

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

Let's first look at 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 f (x) = x2, we need to apply this function to a list [1, 2, 3, 4, 5, 6, 7, 8, 9], you can use map () to implement the following:

Now, we use Python code to implement:

>>> 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, that is, the function object itself.

You may think that you do not need the map () function to write a loop or calculate the result:

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

Yes, but from the previous circular code, can you see at a glance that "f (x) acts on every element of the list and generates a new list of results?

Therefore, map () is a high-order function. In fact, it abstracts operation rules. Therefore, we can not only compute simple f (x) = x2, but also compute any complex functions, for example, convert all the numbers in the list into 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 required.

Let's look at the reduce usage. Reduce acts a function on a sequence [x1, x2, x3. ..] this function must receive two parameters. reduce calculates the result continuation and the next element of the sequence. The effect is:

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

For example, we can use reduce to sum a sequence:

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

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, 3, 5, 7, 9] to an integer of 13579, reduce can be used in the following ways:

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

This example is of little use. However, if the string 'str' is also a sequence, we can write a function that converts 'str' to 'int' with map:

>>> 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 str2int function 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))

Lambda functions can also be further simplified:

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, if Python does not provide the int () function, you can write a function that converts a string to an integer by yourself, and only a few lines of code are required!

Exercise

The map () function is used to change the nonstandard English names entered by the user into uppercase letters and other standard names in lower case. Input: ['Adam ', 'Lisa', 'Bart'], and output: ['Adam ', 'Lisa', 'Bart'].

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.