软硬件环境
- windows 10 64bit
- anaconda3 with python 3.7
视频看这里
此处是youtube的播放链接,需要科学上网。喜欢我的视频,请记得订阅我的频道,打开旁边的小铃铛,点赞并分享,感谢您的支持。
简介
map是python中的一个内置函数,先来看看它的函数定义
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.
可以看出map和之前介绍的 zip 非常相似。第一个参数是一个函数,后面的参数是可迭代的序列,返回值是map对象。
map的功能是将一个序列中的每一个元素依次传入到函数func中,返回的map对象中包含了所有函数调用结果
map的使用示例
In [1]: aList = [1, 2, 3, 4, 5]
In [2]: def add1(x):
...: return x + 1
...:
In [3]: a = map(add1, aList)
In [4]: a
Out[4]: <map at 0x1dd925e7d08>
In [5]: list(a)
Out[5]: [2, 3, 4, 5, 6]
In [6]:
我们定义了函数add1,对参数进行加1操作。将add1和列表aList传入map函数中并将返回值赋给a,可以看到a的类型是map,通过list方法可以看到各个元素的值。有时候为了少写些代码,可以使用lambda函数,如下
In [9]: b = map((lambda x: x+2), aList)
In [10]: list(b)
Out[10]: [3, 4, 5, 6, 7]
In [11]:
最后看个传递多个可迭代序列的示例
In [11]: bList = [5, 4, 3, 2, 1]
In [12]: c = map(lambda x,y: x+y, aList, bList)
In [13]: list(c)
Out[13]: [6, 6, 6, 6, 6]