1 Python官网中关于map的介绍:Python官网中关于map的介绍
map
(
function,
iterable,
...
)
Return an iterator that applies function to every item of iterable, yielding the results. If additional iterable arguments are passed, function must take that many arguments and is applied to the items from all iterables in parallel. With multiple iterables, the iterator stops when the shortest iterable is exhausted. For cases where the function inputs are already arranged into argument tuples, see itertools.starmap()
.
map
(function, iterable, ...)
返回一个迭代器,对iterable的每个项应用function,生成结果。如果传递多个可迭代对象参数,function必须接收这些参数,并应用到从iterables并行提取的项中(可能描述地不太恰当,后面有例子进行介绍)。如果有多个iterable,迭代器在最短的iterable遍历完成时,停止迭代。对于函数的输入已经排列成参数元组的情况,参见itertools.starmap()。
2 Python核心编程中的定义:
map(func,seq[,seq2...]) :将函数func作用于序列(s)的每个元素,并用一个列表来提供返回值;如果func为None,func表现为一个身份函数,返回一个含有每个序列中元素集合的n个元组的列表。
程序举例:>>> mapp = map(square,[1,2,3,4,5])
>>> list(mapp)
[1, 4, 9, 16, 25]
>>> mapp = map(lambda x : x ** 2 , [1,2,3,4,5])
>>> list(mapp)
[1, 4, 9, 16, 25]
含有多个iterable参数时进行并行遍历:
>>> mapp = map(lambda x,y,z:x+y+z,[1,2,3,4,5],[1,2,3,4,5],[1,2,3,4,5])
>>> list(mapp)
[3, 6, 9, 12, 15]
首先观察下面的例子,直接输出map()函数的返回值会出现什么情况。
>>> map(lambda x,y:x+y , [1,2,3],[4,5,6])
再看map()函数的英文介绍——"Return an iterator"。所以,map()函数返回的其实是一个迭代器。(关于迭代器的介绍请参考:Python迭代器小结——伯乐在线)可以使用for循环或list()构造函数,再借助map()函数返回的迭代器,来输出其内容。如下所示:
>>> mapp = map(lambda x,y:x+y , [1,2,3],[4,5,6])
>>> list(mapp)
[5, 7, 9]
>>> list(mapp)
[]
>>> mapp = map(lambda x,y:x+y , [1,2,3],[4,5,6])
>>> for item in mapp:
print(item)
5
7
9
>>> for item in mapp:
print(item)
>>>
上面的方法实际是每次输出时都要生成一个新的list。所以,为了能够实现多次迭代,需要保存生成的list对象。
>>> mapp = map(lambda x,y:x+y , [1,2,3],[4,5,6])
>>> listt = list(mapp)
>>> listt
[5, 7, 9]
>>> listt
[5, 7, 9]
>>> listt = [item for item in mapp]
>>> listt
[5, 7, 9]
>>> listt
[5, 7, 9]
这样,就可以实现多次访问map对象的数据了。
参考网址:
Python 3.x中map对象的访问方式——博客园