在Python中重置生成器对象 [英] Resetting generator object in Python

查看:329
本文介绍了在Python中重置生成器对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个由多个yield返回的生成器对象.准备调用此生成器是相当耗时的操作.这就是为什么我要多次重用生成器.

I have a generator object returned by multiple yield. Preparation to call this generator is rather time-consuming operation. That is why I want to reuse the generator several times.

y = FunctionWithYield()
for x in y: print(x)
#here must be something to reset 'y'
for x in y: print(x)

当然,我会考虑将内容复制到简单列表中.有没有办法重置我的发电机?

Of course, I'm taking in mind copying content into simple list. Is there a way to reset my generator?

推荐答案

另一种选择是使用 itertools.tee() 函数来创建生成器的第二个版本:

Another option is to use the itertools.tee() function to create a second version of your generator:

y = FunctionWithYield()
y, y_backup = tee(y)
for x in y:
    print(x)
for x in y_backup:
    print(x)

如果原始迭代可能无法处理所有项目,那么从内存使用的角度来看这可能是有益的.

This could be beneficial from memory usage point of view if the original iteration might not process all the items.

这篇关于在Python中重置生成器对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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