python map reduce的使用

def square(x):
    return x*x
a=map(square,[1,2,3]) 
print(a)        
#输出为<map object at 0x0033CFB0>   可以看出map返回的实际上是一个map对象
print(list(a))  
#输出为[1, 4, 9]   通过list()方式 显示出来   

#也可以通过for循环来取出内容
ls=[]
for i in a:
    ls.append(i)
print(ls)
#输出为[1, 4, 9]

还可以传入多个参数:

ls1='123'
ls2='abc'
print(list(map(lambda x,y:x+y,ls1,ls2)))
#['1a', '2b', '3c']

如果参数长度不同 按照最短的:

def num(x,y):
    return (x + y)

result = map(num,[1,2,3,4,5,6,7],[1,2,3,4,])
print(list(result))

# [2, 4, 6, 8]

猜你喜欢

转载自blog.csdn.net/redpintings/article/details/81062579