发电机可以使用一次以上吗? [英] Can generator be used more than once?

查看:95
本文介绍了发电机可以使用一次以上吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的代码,其中定义了两个生成器:

This is my piece of code with two generators defined:

one_line_gen = (x for x in range(3))

def three_line_gen():
    yield 0
    yield 1
    yield 2

执行时:

for x in one_line_gen:
    print x

for x in one_line_gen:
    print x

结果符合预期:

0
1
2

但是,如果我执行:

for x in three_line_gen():
    print x

for x in three_line_gen():
    print x

结果是:

0
1
2
0
1
2

为什么?我以为任何生成器只能使用一次.

Why? I thought any generator can be used only once.

推荐答案

three_line_gen不是生成器,它是一个函数.调用它时返回的是一个生成器,每次调用时都会生成一个全新的生成器.每次您这样插入括号:

three_line_gen is not a generator, it's a function. What it returns when you call it is a generator, a brand new one each time you call it. Each time you put parenthesis like this:

three_line_gen()

这是一个需要迭代的全新生成器.但是,如果您要先这样做

It is a brand new generator to be iterated on. If however you were to first do

mygen = three_line_gen()

并遍历mygen两次,第二次将失败,如您所愿.

and iterate over mygen twice, the second time will fail as you expect.

这篇关于发电机可以使用一次以上吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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