因为lambda是匿名函数,map和lambda结合起来使用,代码更加简洁:
求列表list_x = [1, 2, 3, 4, 5, 6, 7, 8],每项的平方
list_x = [1, 2, 3, 4, 5, 6, 7, 8]
r = map(lambda x:x*x,list_x)
print(list(r))
-----------------------------------------
输出:
[1, 4, 9, 16, 25, 36, 49, 64]
lambda
想要再加一个参数呢,其实map
还可以再传入一个参数,
list_x = [1, 2, 3, 4, 5, 6, 7, 8]
list_y = [1, 2, 3, 4, 5, 6, 7, 8]
d = map(lambda x,y:x*x+y,list_x,list_y)
print(list(d))
-------------------------------------
输出:
[2, 6, 12, 20, 30, 42, 56, 72]
如果list_x
和list_y
的长度不相等:
list_x = [1, 2, 3, 4, 5, 6, 7, 8]
list_y = [1, 2, 3]
d = map(lambda x,y:x*x+y,list_x,list_y)
print(list(d))
-----------------------------------
输出:
[2, 6, 12]
list_x = [1, 2, 3,4]
list_y = [1, 2, 3, 4, 5, 6, 7, 8]
d = map(lambda x,y:x*x+y,list_x,list_y)
print(list(d))
-----------------------------------------------
输出:
[2, 6, 12, 20]
通过
map
得到的结果的元素个数取决于传入的两个集合或者序列的最小元素个数。