为什么python生成器只能使用一次? [英] Why can a python generator only be used once?

查看:50
本文介绍了为什么python生成器只能使用一次?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一旦我使用过一次生成器,就无法再使用它.为什么会这样?

Once I use a generator once, it can't be used again. Why is this?

考虑以下代码:

def generator(n):
  a = 1

  for _ in range(n):
    yield a
    a += 1

def run_generator(generator):
  for a in generator:
    print(a, end = " ")

如果我要执行此操作:

count_generator = generator(10)
run_generator(count_generator)
run_generator(count_generator)

它只会打印:

1 2 3 4 5 6 7 8 9 10

基本上,生成器仅在执行一次后就死掉了.

Basically, the generator just dies after a single execution.

我知道生成器只能使用一次的事实是Python内置的东西,但是为什么会这样呢?是否有特定的原因只允许生成器对象执行一次?

I know that the fact that a generator can only be used once is something built into Python, but why is it like this? Is there a specific reason to only allowing a generator object to be executed once?

推荐答案

生成器的工作原理类似于自动报价机.当您在其上拨打 next 时,它会为您提供下一个号码,但是与列表不同,它会忘记.这就是大多数效率的来源.由于它不必记住以前的值,因此内存占用量要小得多(尤其是当并非最终需要所有值时!)

A generator works like ticker tape. When you call next on it, it gives you the next number, but then it forgets it, unlike a list. This is where most of the efficiency comes from. Since it doesn't have to remember what its previous values were, there's a much smaller memory footprint (especially when not all of its values will eventually be needed!)

也许可以重置某些生成器以使其再次运行,但这绝不能保证,如果尝试这样做,某些生成器将彻底失败.Python不是 pure 语言,因此您可能会有生成器在生成值时修改状态.例如,生成器,例如:

Some generators can perhaps be reset to be able to run again, but that's by no means guaranteed, and some generators will outright fail if you try to do that. Python is not a pure language, and so you might have generators that modify state while they produce values. For instance, a generator such as:

def gimme_randoms():
    while True:
        yield random.random()

我可以称之为一堆,但是 random 中PRNG背后的状态每次都会改变.

I can call this a bunch, but the state behind the PRNG in random will change every time I do.

rs = gimme_randoms()
a = next(rs)
b = next(rs)
c = next(rs)  # some numbers

重置此状态意味着什么?好吧,您期望:

What would it mean to reset this state? Well you'd expect:

rs2 = gimme_randoms()
x = next(rs2)
y = next(rs2)
z = next(rs2)

assert a == x and b == y and c == z  # Nonsense!

要保持这种状态,您必须跟踪PRNG的初始状态,然后才能将其种子设置回初始状态.这肯定是可行,但不是生成器的 job 知道其底层实现如何修改状态.

To make this hold, well, you'd have to keep track of the initial state of the PRNG, then have a way to set its seed back to the initial state. That's certainly doable, but it's not the generator's job to know how its underlying implementation has modified state.

这篇关于为什么python生成器只能使用一次?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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