前言
map函数会根据提供的函数对指定序列做映射
一、map函数的语法
map(function, iterable, ...)
其中,function是定义的函数或者匿名函数,iterable是可迭代的列表等,可以有多个列表,用逗号隔开
二、使用方法
list1 = [1,2,3,4,5,6,7]
def my_square(x):
return x**2
map(my_square, list1)
[1, 4, 9, 16, 25, 36, 49]
注意:
- 传递多个列表时,在python3中会根据短的list自动忽略掉长list中多余的元素。
- 在python3中,map的结果返回的是迭代器,需要转成list才能看到结果
list1 = [1,2,3,4,5,6,7]
list2 = [1,2,3,4,5]
map(lambda x, y: x + y, list2,list1)
<map object at 0x10bca1470>
list(map(lambda x, y: x + y, list2,list1))
[2, 4, 6, 8, 10]
Reference
https://zhuanlan.zhihu.com/p/546748039