python map函数迭代 [英] python map function iteration
问题描述
results是一个嵌套列表,看起来像这样:
results is a nested list, and looks like this:
>>> results
[[1, 2, 3, 'a', 'b'], [1, 2, 3, 'c', 'd'], [4, 5, 6, 'a', 'b'], [4, 5, 6, 'c', 'd']]
pr是一个函数,其定义如下:
pr is a function, with definition like this:
>>> def pr(line):
... print line
对结果的常规迭代的行为确实是这样的:
Normal iteration on results does behaves like this:
>>> for result in results:
... pr(result)
...
[1, 2, 3, 'a', 'b']
[1, 2, 3, 'c', 'd']
[4, 5, 6, 'a', 'b']
[4, 5, 6, 'c', 'd']
但是使用map的隐式迭代会导致这种行为:
But implicit iteration with map, results in this behaviour:
>>> map(pr, results)
[1, 2, 3, 'a', 'b']
[1, 2, 3, 'c', 'd']
[4, 5, 6, 'a', 'b']
[4, 5, 6, 'c', 'd']
[None, None, None, None]
我的问题:为什么map函数会产生额外的迭代?
My question: Why does map function produce the additional iteration?
推荐答案
map
将一个函数应用于Iterable的每个元素,并将其结果存储回列表(或Python 3中的map对象)中.因此,[None, None, None, None]
部分是map函数的返回值.您在执行脚本时不会看到此信息,但是您也可以通过将IDID赋值给它来摆脱它:
map
applies a function to each element of the iterable and the result of that is stored back in a list (or map object in Python 3). So the [None, None, None, None]
part is the return value of the map function. You won’t see this when you execute a script, but you can also get rid of it in IDLE by just assigning it to a value:
>>> _ = map(pr, results)
不过请注意,结果列表的构造(至少在Python 2中是有影响的),因此,如果不需要结果,则最好不要使用map
.
Note though, that the construction of the result list (at least in Python 2) has some impact, so if you don’t need the result, you’re better off not using map
in this case.
这篇关于python map函数迭代的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!