python中map函数可迭代那,python map函数迭代

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

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]

My question: Why does map function produce the additional iteration?

解决方案

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)

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值