Python:map () and reduce ()

Source: Internet
Author: User

map()The function receives two parameters, one is a function, the other is a sequence, the map incoming function functions sequentially to each element of the sequence, and returns the result as a new list.

For example, we have a function f (x) =x2, in order to function on a list, you [1, 2, 3, 4, 5, 6, 7, 8, 9] can use the implementation of the map() following:

def f (x):     return x*xmap (f,[1,2,3,4,5,6,7,8,9]

Result

[1, 4, 9, 16, 25, 36, 49, 64, 81]

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)
Practice:

Exercise 1 uses the map() function to change the non-canonical English name entered by the user into the first capitalization, and the other lowercase canonical names. Input: [‘adam‘, ‘LISA‘, ‘barT‘] , Output: [‘Adam‘, ‘Lisa‘, ‘Bart‘] .

For:

def firsttoupper (x):     = X[:1].upper ()    = x[1:].lower ()    = s1 + s2    return S3
Map (firsttoupper,[' AleN ', ' TOM ', ' hello ')

Explanation: X[:1]: The first character of the x string (starting from 0 to 1 subscript but not 1 subscript); X[1:]: x string of the second word selector until finally, that is, from subscript 1 to the end ...

Results:

[' Alen ', ' Tom ', ' Hello ']

Exercise 2 Python provides sum() functions that accept a list and sum, write a prod() function that accepts a list and takes advantage of the quadrature reduce() .

def prod (x, y    ): return x+yreduce (prod,[1,2,3,4,5,6,7,8100])

Results:

8128

Python:map () and reduce ()

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.