本文介绍了屈服直到所有需要的值都屈服,有没有办法让切片变得懒惰的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当生成器未完成值并且已读取所有需要的结果时,有没有办法停止屈服?我的意思是,生成器无需执行StopIteration就可以提供值.

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

我找到了此代码,但尚不了解如何在这种情况下应用它: http://code.activestate.com/recipes/576585-lazy -recursive-generator-function/

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/

推荐答案

这是我想出的最好方法,但是它仍然会进行两次切片以查找长度,并且需要将字符串号从split转换为int:

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:

from time import clock
from random import randint
a=[True for _ in range(randint(1000000,10000000))]
spacing=randint(3,101)
t=clock()
try:
    a[::spacing]=[False]
except ValueError as e:
    a[::spacing]=[False]*int(e.message.rsplit(' ',1)[-1])

print spacing,clock()-t

# baseline

t=clock()
a[::spacing]=[False]*len(a[::spacing])
print 'Baseline:',spacing,clock()-t

我将尽我所能尝试一下,但是它可能不会比根据递归公式进行长度算术更快.通过递归公式改进纯Python主筛子

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

这篇关于屈服直到所有需要的值都屈服,有没有办法让切片变得懒惰的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-25 05:51