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

Source: Internet
Author: User
This article mainly introduces the use of the map () function and the reduce () function in Python, the code is based on the python2.x version, and the friends you need can refer to the following

Python has the map () and reduce () functions built into it.

If you read Google's famous paper "Mapreduce:simplified Data processing on Large Clusters", you can probably understand the concept of map/reduce.

Let's 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 f (x) =x2, to function in a list [1, 2, 3, 4, 5, 6, 7, 8, 9], you can use map () to achieve 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]

Map () The first parameter passed in is F, which is the function object itself.

You might think that you don't need the map () function, write a loop, or you can 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 loop code above, can you see "putting F (x) in every element of the list and generating a new list"?

So, as a higher-order function, map () actually abstracts the arithmetic rules, so we can not only calculate the simple f (x) =x2, but also calculate any complex function, for example, to convert all the list numbers 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 required.

Let's look at the usage of reduce. Reduce functions a function in a sequence [X1, x2, x3 ...] , the function must receive two parameters, and reduce calculates the result and the next element of the sequence, and the effect is:

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

For example, to sum a sequence, it can be implemented with reduce:

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

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, 3, 5, 7, 9] into integers 13579,reduce can come in handy:

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

This example is not very useful in itself, but if you consider that the string str is also a sequence, with a slight change to the above example, with map (), we can write the function that converts str to int:

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

The function that is organized into a str2int is:

def str2int (s):  def fn (x, y):    return x * + 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 lambda functions to further simplify:

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

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

That is, assuming that Python does not provide an int () function, you can write a function that converts the string to an integer by itself, and only requires a few lines of code!

Practice

Using the map () function, the nonstandard English name entered by the user becomes the first letter capitalized, and the other lowercase canonical names. Input: [' Adam ', ' Lisa ', ' Bart '], output: [' Adam ', ' Lisa ', ' Bart '].

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

Related Article

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.