您的位置:首页 > 编程语言 > Python开发

python中的map方法

2018-02-28 22:03 253 查看
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, 4, 9, 16, 25]


如果我们使用Map方法呢

items = [1,2,3,4,5]
lamb'd x:x**2为一个表达式,接受一个参数x并返回x的平方
squared=map(lamdba x:x**2, items)


运行结果:

[1, 4, 9, 16, 25]


map()除了接受一个列表,还可以接受一个列表的函数

def multiply(x):
return x*x
def add(x):
return x+x
func = [multiply, add]
for i in range(10):
value = map(lambda x:x(i), func)
print func​


运行结果:

[0, 0]
[1, 2]
[4, 4]
[9, 6]
[16, 8]
[25, 10]
[36, 12]
[49, 14]
[64, 16]
[81, 18]
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  python