首页 > 编程语言 > 详细

python之map函数

时间:2020-07-01 10:42:32      阅读:53      评论:0      收藏:0      [点我收藏+]

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)

 

python之map函数

原文:https://www.cnblogs.com/mafu/p/13217885.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!