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

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

问题描述

我想计算最大为 n 的平方和.假设 n 是 4.然后这段代码生成一个列表,一个范围为 0 到 4 的地图对象:

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

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

<预><代码>>>>总和(列表(米))14

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

<预><代码>>>>总和(列表(米))0

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

解决方案

map 在 Python 3 中返回一个有状态的迭代器.有状态的迭代器可能只被消耗一次,之后它用完并且不产生任何值.

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

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

m = map(lambda x: x**2, range(0,4))l = 列表(米)断言总和(l)== 14断言总和(l)== 14

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

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

>>> sum(list(m))
14

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

>>> sum(list(m))
0

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 returns a stateful iterator in Python 3. Stateful iterators may be only consumed once, after that it's exhausted and yields no values.

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天全站免登陆