我有一个生成器,它会不断给出遵循特定公式的数字。为了便于讨论,我们假设这是一个函数:
# this is not the actual generator, just an example
def Generate():
i = 0
while 1:
yield i
i+=1
然后,我想从生成器中获取低于某个阈值的数字列表。我正在试着找出一种巨蟒式的方式来做这件事。我不想编辑函数定义。我知道您可以只使用while循环,并以截断为条件,但我想知道是否有更好的方法。我试了一试,但很快就意识到为什么它不能工作。
l = [x for x in Generate() x<10000] # will go on infinitely
那么,有没有正确的方法来做到这一点。
谢谢
发布于 2013-02-02 05:04:49
将您的生成器包装在另一个生成器中:
def no_more_than(limit):
def limiter(gen):
for item in gen:
if item > limit:
break
yield item
return limiter
def fib():
a,b = 1,1
while 1:
yield a
a,b = b,a+b
cutoff_at_100 = no_more_than(100)
print list(cutoff_at_100(fib()))
打印:
[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
https://stackoverflow.com/questions/14653870
复制相似问题