Python地图,列表(地图),lambda和性能 [英] python map, list(map), lambda and performance

查看:186
本文介绍了Python地图,列表(地图),lambda和性能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我现在已经成为程序员程序员,只是试图将我的思维转换为使用函数式编程(现在是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 函数何时会被触发?


map 函数在编程人员术语中称为 lazy 。它不会做任何工作,除非必须。这在函数式编程中更广泛地被称为 懒惰评估 。而不是立即计算任何值, map 函数返回所谓的 迭代 的。通过这样做,它将委托给它的值计算给你。
$ 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]
>>>


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 map and list(map(..))

Lets say I have a simple 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)

Now, when I try to do the following

map(lambda x: print(x), arr)

nothing happens, UNTIL, i wrap this in a list and it does my super heavy print function:

list(map(lambda x: print(x), arr))

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 print function going to be triggered then?

解决方案

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 print function going to be triggered then?

The 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.

A single value can be computed by the iterator using next:

>>> arr = [1, 2, 3]
>>> it = map(lambda x: print(x), arr)
>>> next(it)
1
>>> 

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:

>>> it = map(lambda x: print(x), arr)
>>> list(it)
1
2
3
4
[None, None, None, None]
>>> 

这篇关于Python地图,列表(地图),lambda和性能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆