Python迭代器在对其执行一些操作后为空 [英] Python iterator is empty after performing some action on it

查看:67
本文介绍了Python迭代器在对其执行一些操作后为空的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在 python3 中对 codeeval 进行挑战,但在尝试改进我的解决方案时陷入困境.每次我尝试在同一个迭代器上连续两次迭代(或打印或其他操作)时,第二个循环都是空的.这是一个产生这种行为的最小示例,尽管我尝试了几种不同的列表组合,但结果相同:

numbers = ('1','2','3','4','5')数字 = 地图(整数,数字)打印(列表(数字))打印(列表(数字))

结果:

[1, 2, 3, 4, 5][]

为什么打印(在这种情况下)会删除数字的内容?

解决方案

这正是迭代器的工作方式.它们旨在仅一次即时生成数据,仅此而已.如果您想再次从中获取数据,则必须将所有迭代数据保存到另一个列表中,或者再次启动迭代器.如果您需要从文件中读取数据或做其他烦人的事情来重新获取迭代器,最好在生成数据时将其存储在列表中.

<预><代码>>>>数字 = ('1','2','3','4','5')>>>ints = [x for x in map(int, numbers)]>>>打印(列表(整数))[1, 2, 3, 4, 5]>>>打印(列表(整数))[1, 2, 3, 4, 5]

https://docs.python.org/2/library/stdtypes.html#iterator-types

<块引用>

协议的意图是一旦迭代器的 next() 方法引发 StopIteration,它将在后续调用中继续这样做.不遵守此属性的实现被视为已损坏.(此约束是在 Python 2.3 中添加的;在 Python 2.2 中,各种迭代器根据此规则被破坏.)

我应该注意,我在 Python 2.4.3 上运行了您提供的确切代码,并且每次都打印出列表.所以我想这是一个版本相关的东西.

I was trying to do a challenge on codeeval in python3 and got stuck trying to improve my solution. Every time i tried to iterate (or print, or some other action) two times consecutively over the same iterator, the second loop came up empty. Here is a minimal example that produces this behavior, although I tried several different combinations with lists etc. that gave me the same result:

numbers = ('1','2','3','4','5')
numbers = map(int, numbers)                                                    
print(list(numbers))                                                          
print(list(numbers))

results in:

[1, 2, 3, 4, 5]
[]

Why does print (in this case) delete the content of numbers?

解决方案

This is exactly how iterators work. They're designed to generate data on the fly exactly one time, no more. If you want to get data out of it a second time, you either have to save all the iterated data to another list, or initiate the iterator again. In cases where you need to read from files or do other annoying things to re-obtain that iterator, it's probably best to just store that data in a list when it's generated.

>>> numbers = ('1','2','3','4','5')
>>> ints = [x for x in map(int, numbers)]
>>> print(list(ints))
[1, 2, 3, 4, 5]
>>> print(list(ints))
[1, 2, 3, 4, 5]

https://docs.python.org/2/library/stdtypes.html#iterator-types

The intention of the protocol is that once an iterator’s next() method raises StopIteration, it will continue to do so on subsequent calls. Implementations that do not obey this property are deemed broken. (This constraint was added in Python 2.3; in Python 2.2, various iterators are broken according to this rule.)

I should note that I ran the exact code you gave on Python 2.4.3, and it printed out the list every time. So it's a version dependent thing, I suppose.

这篇关于Python迭代器在对其执行一些操作后为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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