Python Generator Cutoff

Hoo*_*ady 2 python generator python-2.7

我有一个发电机,将继续提供遵循特定公式的数字.为了论证,让我们说这是函数:

# this is not the actual generator, just an example
def Generate():
    i = 0
    while 1:
        yield i
        i+=1       
Run Code Online (Sandbox Code Playgroud)

然后,我想从该生成器获得低于特定阈值的数字列表.我试图弄清楚这样做的pythonic方法.我不想编辑函数定义.我意识到你可以使用一个带有截止值的while循环作为条件,但我想知道是否有更好的方法.我试了一下,但很快意识到为什么它不起作用.

l = [x for x in Generate() x<10000] # will go on infinitely
Run Code Online (Sandbox Code Playgroud)

那么有没有正确的方法来做到这一点.

谢谢

Lev*_*sky 11

itertools创建另一个迭代器的解决方案:

from itertools import takewhile
l = takewhile(lambda x: x < 10000, generate())
Run Code Online (Sandbox Code Playgroud)

list()如果您确定需要列表,请将其包装:

l = list(takewhile(lambda x: x < 10000, generate()))
Run Code Online (Sandbox Code Playgroud)

或者,如果你想要一个清单,就像发明轮子一样:

l = []
for x in generate():
    if x < 10000:
        l.append(x)
    else:
        break
Run Code Online (Sandbox Code Playgroud)