Skip to content

Files

Latest commit

ff312a5 · Jun 26, 2020

History

History
214 lines (148 loc) · 3.67 KB

38.md

File metadata and controls

214 lines (148 loc) · 3.67 KB

Python map()函数

原文: https://thepythonguru.com/python-builtin-functions/map/


于 2020 年 1 月 7 日更新


map()内置函数应用于序列中的每个项目后,它会返回一个迭代器。 其语法如下:

语法map(function, sequence[, sequence, ...]) -> map object

Python 3

>>>
>>> map(ord, ['a', 'b', 'c', 'd'])
<map object at 0x7f36fac76dd8>
>>>
>>> list(map(ord, ['a', 'b', 'c', 'd']))
>>> [97, 98, 99, 100]
>>>
map_obj = map(ord, ['a', 'b', 'c', 'd'])
print(map_obj)
print(list(map_obj)) 

在此,列表中的项目一次被传递到ord()内置函数。

由于map()返回一个迭代器,因此我们使用了list()函数立即生成结果。

上面的代码在功能上等同于以下代码:

Python 3

>>>
>>> ascii = []
>>>
>>> for i in ['a', 'b', 'c', 'd']:
...   ascii.append(ord(i))
...
>>>
>>> ascii
[97, 98, 99, 100]
>>>
ascii = []

for i in ['a', 'b', 'c', 'd']:
    ascii.append(ord(i))

print(ascii) 

但是,使用map()会导致代码缩短,并且通常运行速度更快。

在 Python 2 中,map()函数返回一个列表,而不是一个迭代器(就内存消耗而言,这不是很有效),因此我们无需在list()调用中包装map()

Python 2

>>>
>>> map(ord, ['a', 'b', 'c', 'd']) # in Python 2
[97, 98, 99, 100]
>>>

传递用户定义的函数


在下面的清单中,我们将用户定义的函数传递给map()函数。

Python 3

>>>
>>> def twice(x):
...     return x*2
...
>>>
>>> list(map(twice, [11,22,33,44,55]))
[22, 44, 66, 88, 110]
>>>
def twice(x):
    return x*2

print(list(map(twice, [11,22,33,44,55]))) 

在此,该函数将列表中的每个项目乘以 2。

传递多个参数


如果我们将n序列传递给map(),则该函数必须采用n个参数,并且并行使用序列中的项,直到用尽最短的序列。 但是在 Python 2 中,当最长的序列被用尽时,map()函数停止,而当较短的序列被用尽时,None的值用作填充。

Python 3

>>>
>>> def calc_sum(x1, x2):
...     return x1+x2
...
>>>
>>> list(map(calc_sum, [1, 2, 3, 4, 5], [10, 20, 30]))
[11, 22, 33]
>>>
def calc_sum(x1, x2):
    return x1+x2

map_obj = list(map(calc_sum, [1, 2, 3, 4, 5], [10, 20, 30]))
print(map_obj) 

Python 2

>>>
>>> def foo(x1, x2):
...     if x2 is None:
...         return x1
...     else:
...         return x1+x2
...
>>>
>>> list(map(foo, [1, 2, 3, 4, 5], [10, 20, 30]))
[11, 22, 33, 4, 5]
>>>

传递 Lambda


如果您的函数不打算被重用,则可以传递 lambda(内联匿名函数)而不是函数。

Python 3

>>> 
>>> list(map(lambda x1:x1*5, [1, 2, 3]))
[5, 10, 15]
>>>
map_obj = map(lambda x1:x1*5, [1, 2, 3])
print(list(map_obj)) 

在此,该函数将列表中的每个项目乘以 5。

配对项目(仅在 Python 2 中)


最后,您可以通过传递None代替函数来配对多个序列中的项目:

Python 2

>>> 
>>> map(None, "hello", "pi")
[('h', 'p'), ('e', 'i'), ('l', None), ('l', None), ('o', None)]
>>>

请注意,当较短的序列用尽时,将使用None填充结果。

这种形式的map()在 Python 3 中无效。

>>> 
>>> list(map(None, "hello", "pi"))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'NoneType' object is not callable
>>>
print(list(map(None, "hello", "pi"))) 

如果要配对多个序列中的项目,请使用zip()函数。