# Python函数之map( )

#### 一 map()函数介绍

Python官网中关于map的介绍：Python官网中关于map的介绍

`map` ( functioniterable... )

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`(functioniterable...)

```>>> 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]```

```>>> 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 object at 0x00000241D42C2550>```
再看map()函数的英文介绍——"Return an iterator"。所以，map()函数返回的其实是一个迭代器。（关于迭代器的介绍请参考：Python迭代器小结——伯乐在线

```>>> 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)

>>> ```

这样是可以输出内容，但是只能输出一次。原因是：迭代器对象不支持重新迭代，即同一个迭代器对象不支持多次迭代。
在迭代器对象的内部，其遍历机制实际是调用其内部函数__next__()来获取容器的下一个元素，当后面没有元素时，就抛出StopIteration异常。详细介绍请参考：Python迭代器小结——伯乐在线

```>>> 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]```