地圖()

map() 是一個內建函式,可用於將函式應用於 iterable 的元素。在 Python 2 中,map 返回一個列表。在 Python 3 中,map 返回一個地圖物件,它是一個生成器。

# Python 2.X
>>> map(str, [1, 2, 3, 4, 5])
['1', '2', '3', '4', '5']
>>> type(_)
>>> <class 'list'>

# Python 3.X
>>> map(str, [1, 2, 3, 4, 5])
<map object at 0x*>
>>> type(_)
<class 'map'>

# We need to apply map again because we "consumed" the previous map....
>>> map(str, [1, 2, 3, 4, 5])
>>> list(_)
['1', '2', '3', '4', '5']

在 Python 2 中,你可以傳遞 None 作為身份函式。這在 Python 3 中不再有效。

Python 2.x >= 2.3

>>> map(None, [0, 1, 2, 3, 0, 4])
[0, 1, 2, 3, 0, 4]

Python 3.x >= 3.0

>>> list(map(None, [0, 1, 2, 3, 0, 5]))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'NoneType' object is not callable

此外,當在 Python 2 中傳遞多個可迭代的引數時,mapNone 填充較短的迭代(類似於 itertools.izip_longest)。在 Python 3 中,迭代在最短迭代之後停止。

在 Python 2 中:

Python 2.x >= 2.3

>>> map(None, [1, 2, 3], [1, 2], [1, 2, 3, 4, 5])
[(1, 1, 1), (2, 2, 2), (3, None, 3), (None, None, 4), (None, None, 5)]

在 Python 3 中:

Python 3.x >= 3.0

>>> list(map(lambda x, y, z: (x, y, z), [1, 2, 3], [1, 2], [1, 2, 3, 4, 5]))
[(1, 1, 1), (2, 2, 2)]

# to obtain the same padding as in Python 2 use zip_longest from itertools
>>> import itertools
>>> list(itertools.zip_longest([1, 2, 3], [1, 2], [1, 2, 3, 4, 5]))
[(1, 1, 1), (2, 2, 2), (3, None, 3), (None, None, 4), (None, None, 5)]

注意 :代替 map 考慮使用與 Python 2/3 相容的列表推導。取代 map(str, [1, 2, 3, 4, 5])

>>> [str(i) for i in [1, 2, 3, 4, 5]]
['1', '2', '3', '4', '5']