Python迭代器在对其执行某些操作后为空
问题描述
我试图在 python3 中对 codeeval 进行挑战,但在试图改进我的解决方案时遇到了困难.每次我尝试在同一个迭代器上连续两次迭代(或打印或其他操作)时,第二个循环都是空的.这是一个产生这种行为的最小示例,尽管我尝试了几种与列表等不同的组合,但结果相同:
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))
结果:
[1, 2, 3, 4, 5]
[]
为什么 print(在这种情况下)会删除数字的内容?
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
协议的意图是一旦迭代器的 next() 方法引发 StopIteration,它将在后续调用中继续这样做.不遵守此属性的实现被视为已损坏.(此约束是在 Python 2.3 中添加的;在 Python 2.2 中,各种迭代器根据此规则被破坏.)
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.)
我应该注意,我在 Python 2.4.3 上运行了您提供的确切代码,并且每次都打印出列表.所以这是一个版本依赖的事情,我想.
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.
相关文章