Python地图,列表(地图),lambda和性能 [英] python map, list(map), lambda and performance
问题描述
我现在已经成为程序员程序员,只是试图将我的思维转换为使用函数式编程(现在是Python 3)。
因此,我试图去掌握 map
和 list(map()之间的交互,而不是写for-each循环。 。))
假设我有一个简单的 for-in
循环,一些资源沉重的计算(为简单起见,我将用 print
替换):
arr = [1,2,3,4]
for arr:
print(x)
现在,当我尝试执行以下操作时:
map(lambda x:print(x),arr)
什么也没有发生,直到我将它包装在一个列表中,它使我的超重 print
函数:
list(map(lambda x:print(x),arr))
为什么?我错过了什么?我了解map会返回一个应该节省内存的迭代器,而不是马上保存整个列表。但是,当我的超级大 print
函数会被触发吗?
< blockquote>
为什么?我错过了什么?我了解map会返回一个应该节省内存的迭代器,而不是马上保存整个列表。但是,我的超级重量 print
函数何时会被触发?
迭代器可以使用 但是,当您将映射迭代器转换为列表时,您迫使映射计算所有它的值,从而调用你的函数: I've been a procedural programmer for a while now, and just trying to switch my mindset to use functional programming (in Python 3 for now).
So, instead of writing a for-each loop, I'm trying to grasp the interaction between Lets say I have a simple Now, when I try to do the following nothing happens, UNTIL, i wrap this in a list and it does my super heavy Why? What am I missing? I understand map returns an iterator which is supposed to save memory instead of just holding the entire list right away. But when is my super heavy Why? What am I missing? I understand map returns an iterator which is supposed to save memory instead of just holding the entire list right away. But when is my super heavy The A single value can be computed by the iterator using However, when you casted the map iterator to be a list, you were forcing map to compute all of its values and thus call your function:
这篇关于Python地图,列表(地图),lambda和性能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋! map
函数在编程人员术语中称为 lazy 。它不会做任何工作,除非必须。这在函数式编程中更广泛地被称为 懒惰评估 。而不是立即计算任何值,
$ b next
来计算一个值:
>>> arr = [1,2,3]
>>> it = map(lambda x:print(x),arr)
>>> next(it)
1
>>>
>>> it = map(lambda x:print(x),arr)
>>>列表(it)
1
2
3
4
[None,None,None,None]
>>>
map
and list(map(..))
for-in
loop which does some resource heavy computation (which I'll replace with print
here for the sake of simplicity):arr = [1,2,3,4]
for x in arr:
print(x)
map(lambda x: print(x), arr)
print
function:list(map(lambda x: print(x), arr))
print
function going to be triggered then?
print
function going to be triggered then?map
function is what's commonly known in programmer terminology as lazy. It won't do any work unless it has to. This is more broadly known as in functional programming as lazy evaluation. Rather than immediately compute any values, the map
function instead returns what's known as an iterator. By doing this, it's delegating the job of compute the values it was given back to you. next
:>>> arr = [1, 2, 3]
>>> it = map(lambda x: print(x), arr)
>>> next(it)
1
>>>
>>> it = map(lambda x: print(x), arr)
>>> list(it)
1
2
3
4
[None, None, None, None]
>>>