**map类** 咱们在匿名函数那一讲使用了 map 类,现在来探讨下 map 类是做什么的。 map 在Python3.5 中的源码,只摘录了下面咱们比较关注的部分 ~~~ class map(object): """ 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. """ def __init__(self, func, *iterables): # real signature unknown; restored from __doc__ pass ~~~ map 函数实际上调用的是 map 类,在初始化该累的时候,需要传入一个方法,还有一个可迭代对象,map 将传入的函数依次作用到序列的每个元素,并把结果作为新的 Iterator 返回。 举例说明:map 处理字符串 ~~~ >>> def strLower(s):return s.lower() ... >>> map(strLower,'AirVip') <map object at 0x7f9c3db02b70> >>> >>> list(map(strLower,'AirVip')) ['a', 'i', 'r', 'v', 'i', 'p'] ~~~ 如图所示 ![map](https://box.kancloud.cn/b20585895f8dc742e34656410793ef11_228x172.png) 从代码中我么可以看出 map() 传入的第一个参数是函数 strLower,调用之后,我们得到了一个 map 对象(Iterator),Iterator 是惰性序列,因需要通过 list() 函数让它把整个序列都计算出来并返回一个 list,我们就看到最终的结果了。 **Demo** 将 数字字符串 转换成 整形 列表 ~~~ >>> def char2num(s):return {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}[s] ... >>> list(map(char2num,'12345')) [1, 2, 3, 4, 5] ~~~ map 使用匿名函数 ~~~ >>> list(map(lambda x:x*x,[1,2,3,4,5])) [1, 4, 9, 16, 25] ~~~