Python map () function

Source: Internet
Author: User

Python map () function
1. Description

The map function in python is applied to every iteratable item, and a result list is returned. If other iteratable parameters are passed in, the map function iterates each parameter with the corresponding processing function. 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.

Map (function, iterable ,...)

2. For example, there is a list, L = [1,2,3,4,5,6,7,8]To apply f (x) = x ^ 2 to this list, we can use the map function for processing.
 
>>> L = [1,2,3,4,]
>>> def pow2(x):
... return x*x
...
>>> map(pow2,L)
[1, 4, 9, 16]

If an additional iteratable parameter is provided, 'function' is applied to each element of the iteratable parameter at the same time '.
>>> def mknum(a,b,c):...     return a*10000+b*100+c... >>> l1 = [10,20,30]>>> l2 = [40,50,60]>>> l3 = [70,80,90]>>> map(mknum,l1,l2,l3)[104070, 205080, 306090]

The results show that the map function performs the mknum function to obtain the same subscript for each list.

3. Small tasks

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'].

  #!/usr/bin/env python    def chname(name):     n = 0    for a in name:        if n==0:            cname = a.upper()        else:            cname = cname + a.lower()        n = n+1    return cname    print map(chname,['bob','jeAN','jessica'])

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.