如何创建python迭代器的副本?

如何创建python迭代器的副本?,python,python-2.7,python-3.x,iterator,Python,Python 2.7,Python 3.x,Iterator,在python中,我尝试使用赋值创建迭代器的副本,但是它创建了一个迭代器的副本,该副本引用了原始迭代器本身。例如: 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 ) #i

在python中,我尝试使用赋值创建迭代器的副本,但是它创建了一个迭代器的副本,该副本引用了原始迭代器本身。例如:

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都引用相同的迭代器对象。是否可以创建不引用原始对象的迭代器对象的副本?

注意 这个问题是关于如何通过值创建迭代器对象的副本。因此,对于我的列表中的项目,不要提及类似解决方案的

提前感谢

使用制作副本;它们使用缓冲区在不同迭代器之间共享结果:

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形三通

请注意,缓冲区还意味着,如果您将其中一个拷贝提前到其他拷贝之前,那么这些拷贝可能会产生巨大的内存开销!从文件中:

此itertool可能需要大量辅助存储(取决于需要存储的临时数据量)。通常,如果一个迭代器在另一个迭代器启动之前使用了大部分或全部数据,那么使用
list()
而不是
tee()
会更快


我尝试了
copy.copy()
,它也起了作用。也许有一个隐藏的陷阱?@Jean-Françoisfare:这对发电机不起作用。请尝试使用使用
而为True:yield random.random()
的生成器。例如,可能与“您不能对生成器进行pickle”相关。@Jean Françoisfare:仅仅因为某些迭代器对象是可复制的,并不意味着它们都是可复制的。该示例生成一个
list\u迭代器()
对象,它只需要存储对原始list对象的引用和当前位置。那很容易复制。但对于一个无止境的随机发生器来说,没有“当前位置”,只有可能产生下一个值的东西。