python之map函数

map()函数会根据提供的函数对指定序列做映射。语法如下:

map(func, *iterables) --> map object
 |  
 |  Make an iterator that computes the function using arguments from
 |  each of the iterables.  Stops when the shortest iterable is exhausted.

参数:
func -- 函数
iterable -- 一个或多个序列

返回值:
python2.x返回列表
python3.x返货迭代器

用法1:

1 def square(x): #定义函数
2     return x**2 #返回值为x的平方
3 
4 a = map(square, [1,2,3,4,5]) #调用map并赋值给a
5 print(list(a)) #打印list a

用法2,与lambda函数结合使用:

b = map(lambda x:x**2, [1,2,3,4,5]) #定义变量b,将lambda表达式作为函数传给map

print(list(b))

用法3,两个列表相同位置的元素相加:

1 c = [1,3,5,7,9] #列表
2 d = [2,4,6,8,10] #列表
3 
4 f = map(lambda x,y:x+y, c, d) #相加
5 print(f)

 

posted @ 2020-07-01 10:37  、一叶孤城  阅读(685)  评论(0编辑  收藏  举报