直到所有需要的值都产生为止,有没有办法让切片变得懒惰
当生成器未完成值并且所有需要的结果已被读取时,是否有方法停止生成?我的意思是生成器在不执行 StopIteration 的情况下给出值。
例如,这永远不会停止:(修订)
from random import randint
def devtrue():
while True:
yield True
answers=[False for _ in range(randint(100,100000))]
answers[::randint(3,19)]=devtrue()
print answers
我找到了这段代码,但还不明白如何在这种情况下应用它: http://code.activestate.com/recipes/576585-lazy -递归生成器函数/
Is there way to stop yielding when generator did not finish values and all needed results have been read? I mean that generator is giving values without ever doing StopIteration.
For example, this never stops: (REVISED)
from random import randint
def devtrue():
while True:
yield True
answers=[False for _ in range(randint(100,100000))]
answers[::randint(3,19)]=devtrue()
print answers
I found this code, but do not yet understand, how to apply it in this case:
http://code.activestate.com/recipes/576585-lazy-recursive-generator-function/
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以在生成器对象上调用
close()
。这样,生成器内就会引发GeneratorExit
异常,并且进一步调用其next()
方法将引发StopIteration
:You can call
close()
on the generator object. This way, aGeneratorExit
exception is raised within the generator and further calls to itsnext()
method will raiseStopIteration
:正如您已经看到的,
并且您编写
devtrue
的方式不应该停止。如果你需要这种能力,你可以:或者更简单地说:
如果你制造一个无限的发电机,它将无限地产生。
As you have already seen,
And the way you have written
devtrue
it shouldn't stop. If you need that capacity you could:or far more simply:
If you make an infinite generator, it will generate infinitely.
与 Haskell 中的
take
函数类似,您可以基于另一个生成器构建一个“有限”生成器:您可以使用“until”生成器、“while”等进一步扩展这个想法
。 一样使用它
像...
In analogy with the
take
function in Haskell, you can build a 'limited' generator based upon another generator:You can further this idea with an "until" generator, a "while", ...
And use it like
...
这是我想出的最好的方法,但它仍然会进行两次切片以找到长度,并且需要将字符串号从分割转换为整数:
我将在我的素筛上尝试它,但它可能不会比执行更快递归公式的长度算术。
通过递归公式改进纯Python素数筛
This is best I came up with, but it does still the slicing twice to find the length and need to convert string number from splitting to int:
I will try it to my prime sieve, but it is likely not to be faster than doing the length arithmetic from recurrence formula.
Improving pure Python prime sieve by recurrence formula