简体   繁体   English

Python map / filter / reduce with function或anonymous function

[英]Python map/filter/reduce with function or anonymous function

When I do this at command line (same for filter and reduce) 当我在命令行执行此操作时(同样用于过滤器和减少)

map( lambda x: x+1, [1,2,3,4,5] )

instead of a list/collection as a result... i got 结果而不是列表/集合......我得到了

<map object at 0x6ffffe7b630>

to obtain the list I have to apply the list() function same happens if I use a plain old function to replace the lambda... 要获取列表我必须应用list()函数,如果我使用普通的旧函数来替换lambda ...

Why this behavior ? 为什么会这样?

Because many of the iteration functions use 'lazy' evaluation. 因为许多迭代函数使用“懒惰”评估。 Namely, they don't apply the function immediately all elements of the list. 即,它们不立即应用该功能列表的所有元素。 Instead they use a coroutine to apply the function one at a time as the "map object" is iterated. 相反,当迭代“地图对象”时,他们使用协程一次应用一个函数。

This is a performance feature when some (but not all) of the items will be iterated, or might not need to be determined all at once. 当一些(但不是全部)项目将被迭代时,或者可能不需要一次确定所有项目时,这是一个性能特征。 The lambda is applied only as needed. lambda仅在需要时应用。 Previous versions of python didn't have this optimization and instead just applied the lambda to everything once map is called. 以前版本的python没有这个优化,而只是在调用map后将lambda应用于所有内容。

The function map doesn't return a list, but an iterator 函数map不返回列表,而是返回迭代器

Return an iterator that applies function to every item of iterable, yielding the results. 返回一个迭代器,它将函数应用于每个iterable项,从而产生结果。

The documentation for map has more information. 地图文档有更多信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM