问题描述
在python中,我尝试使用赋值创建迭代器的副本,但是它创建了一个迭代器的副本,它引用了原始迭代器本身。例如:
In python i tried to create a copy of my iterator with using assignment however it create a copy of iterator which reference to the original iterator itself. For instance:
my_list = [5, 4, 3,2]
first_it = iter(my_list)
second_it = first_it
print next(first_it ) #it will print 5
print next(second_it) #it will print 4
print next(first_it ) #it will print 3
正如您在示例中看到的,first_it和second_it都引用相同的迭代器对象。是否可以创建一个不参考原始对象的迭代器对象副本?
As you see in the example first_it and second_it both refer to same iterator object. Is it possible to create a copy of iterator object which is not reference to the original object?
注意
这个问题是如何按值创建迭代器对象的副本。所以不要在my_list中提及项目:
就像解决方案一样。
提前谢谢
NoteThis question is about how to creating a copy of iterator object by value. So don't mention for item in my_list:
like solutions.
Thanks in advance
推荐答案
使用以生成副本;这些使用缓冲区在不同的迭代器之间共享结果:
Use the itertools.tee()
function to produce copies; these use a buffer to share results between different iterators:
from itertools import tee
my_list = [5, 4, 3,2]
first_it = iter(my_list)
first_it, second_it = tee(first_it)
print next(first_it) # prints 5
print next(second_it) # prints 5
print next(first_it) # prints 4
注意你不应该更长时间使用原始迭代器;只使用T恤。
Note that you should no longer use the original iterator; use only the tees.
请注意,缓冲区还意味着如果您将其中一个副本推进到其他副本之前,这些内容可能会产生巨大的内存成本!从文档:
Note that the buffer also means that these can incur a significant memory cost if you advance one of the copies far ahead of the others! From the documentation:
这篇关于如何创建python迭代器的副本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!