Python:在地图对象上两次调用“列表" [英] Python: calling 'list' on a map object twice

查看:67
本文介绍了Python:在地图对象上两次调用“列表"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想计算n的平方和.假设n为4,则此代码生成一个列表,列出范围为0到4的地图对象:

I wanted to calculate the sum of squares up to n. Say n is 4. Then this code generates a list a map object in the range 0 to 4:

m = map(lambda x: x**2, range(0,4))

足够轻松.现在在m上调用列表,然后求和:

Ease enough. Now call list on m, and then sum:

>>> sum(list(m))
14

意外的行为是,如果我再次运行最后一行,则总和为0:

The unexpected behavior is that if I run the last line again, the sum is 0:

>>> sum(list(m))
0

我怀疑这是因为调用list(m)返回一个空列表,但是我找不到对此行为的解释.有人可以帮我吗?

I suspect that this is because calling list(m) returns an empty list, but I can't find an explanation for this behavior. Can someone help me out with this?

推荐答案

map在Python 3中返回一个有状态的迭代器.有状态的迭代器可能只消耗一次,在耗尽后不会产生任何值.

map returns a stateful iterator in Python 3. Stateful iterators may be only consumed once, after that it's exhausted and yields no values.

在代码段中,您多次使用迭代器. list(m)每次尝试重新创建列表时,对于第二次和下一次运行,创建的列表将始终为空(因为在第一次list(m)操作中消耗了源迭代器).

In your code snippet you consume iterator multiple times. list(m) each time tries to recreate list, and for second and next runs created list will always be empty (since source iterator was consumed in first list(m) operation).

只需将迭代器转换为列表一次,然后在该列表上进行操作.

Simply convert iterator to list once, and operate on said list afterwards.

m = map(lambda x: x**2, range(0,4))
l = list(m)
assert sum(l) == 14
assert sum(l) == 14

这篇关于Python:在地图对象上两次调用“列表"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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