【发布时间】:2018-06-08 11:56:47
【问题描述】:
我一直在尝试使用 Python 中的 map 函数,但遇到了一些麻烦。我不知道哪些是将函数 foo 映射到列表栏的正确方法:
map(foo, bar)
或
newBar = map(foo, bar)
我从不同的网站得到了不同的结果。以下哪个是正确的用法?
【问题讨论】:
标签: python list return-type
我一直在尝试使用 Python 中的 map 函数,但遇到了一些麻烦。我不知道哪些是将函数 foo 映射到列表栏的正确方法:
map(foo, bar)
或
newBar = map(foo, bar)
我从不同的网站得到了不同的结果。以下哪个是正确的用法?
【问题讨论】:
标签: python list return-type
map 返回一个新列表,并且不会更改您在函数中输入的列表。所以,用法是:
def foo(x): #sample function
return x * 2
bar = [1, 2, 3, 4, 5]
newBar = map(foo, bar)
在解释器中:
>>> print bar
[1, 2, 3, 4, 5]
>>> print newBar
[2, 4, 6, 8, 10]
注意:这是python 2.x
【讨论】:
在 Python 2 中,map() 返回一个新列表。在 Python 3 中,它返回一个迭代器。您可以将其转换为列表:
new_list = list(map(foo, bar))
顾名思义,迭代器的常见用途是对其进行迭代:
for x in map(foo, bar):
# do something with x
这一次生成一个值,而不像创建列表那样将所有值都放入内存。
此外,您可以通过迭代器执行单步操作:
my_iter = map(foo, bar)
first_value = next(my_iter)
second_value = next(my_iter)
现在与其余部分一起工作:
for x in map(foo, bar):
# x starts from the third value
这在 Python 3 中很常见。zip 和 enumerate 也返回迭代器。这通常称为惰性求值,因为只有在真正需要时才会产生值。
【讨论】: