1. Description
The map function in Python is applied to each iteration of an item and returns a list of results. If other iterative parameters are passed in, the map function iterates through each parameter with the corresponding processing function. 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.
Map (function, iterable, ...)
2. For example
- With a list,
L = [1,2,3,4,5,6,7,8]
we're going to work with F (x) =x^2 on this list, so we can use the map function.
>>> L = [1,2,3,4,]
>>> def pow2(x):
... return x*x
...
>>> map(pow2,L)
[1, 4, 9, 16]
- If an additional iteration parameter is given, the ' function ' is applied simultaneously to each element in the iteration parameter.
>>> 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)[104070205080306090]
The results show that the map function deals with the Mknum function of each list by taking the same subscript.
3. Small Tasks
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 '].
#!/usr/bin/env python def chname(name): 0 forin name: if n==0: cname = a.upper() else: cname = cname + a.lower() n = n+1 return cname print map(chname,[‘bob‘,‘jeAN‘,‘jessica‘])
Python map () function