map函数接受两个参数,一个是函数,一个是序列,map对items中的每个元素依次执行function,并把结果作为新的list返回
语法:
map(function_to_apply, list_of_inputs)
返回一个列表中数字的平方,通常我们会这么做
items = [1,2,3,4,5]squared = []for i in items: squared.append(i**2)print squared
1
2
3
4
5
运行结果:
[1, 4, 9, 16, 25]
1
如果我们使用Map方法呢
items = [1,2,3,4,5]lamb"d x:x**2为一个表达式,接受一个参数x并返回x的平方squared=map(lamdba x:x**2, items)
1
2
3
运行结果:
[1, 4, 9, 16, 25]
1
map()除了接受一个列表,还可以接受一个列表的函数
def multiply(x): return x*xdef add(x): return x+xfunc = [multiply, add]for i in range(10): value = map(lambda x:x(i), func) print func
1
2
3
4
5
6
7
8
运行结果:
[0, 0][1, 2][4, 4][9, 6][16, 8][25, 10][36, 12][49, 14][64, 16][81, 18]
1
2
3
4
5
6
7
8
9
10