python map lambda_Python地图,列表(地图),lambda和性能

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 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]

>>>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值