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