文档定义:
map
(function, iterable, ...)
Return an iterator that applies function to every item of iterable, yielding the results. If additional iterablearguments 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 以参数可迭代对象(序列)中的每一个元素调用 function 函数
Python 2.x返回列表
Python 3.x返回迭代器
实例:
>>>def square(x) : # 计算平方数
... return x ** 2
...
>>> map(square, [1,2,3,4,5]) # 计算列表各个元素的平方
[1, 4, 9, 16, 25]
>>> map(lambda x: x ** 2, [1, 2, 3, 4, 5]) # 使用 lambda 匿名函数
[1, 4, 9, 16, 25]
# 提供了两个列表,对相同位置的列表数据进行相加
>>> map(lambda x, y: x + y, [1, 3, 5, 7, 9], [2, 4, 6, 8, 10])
[3, 7, 11, 15, 19]
注意:map()函数不改变原有的 list,而是返回一个新的 list。