我有一个生成器,它会不断给出遵循特定公式的数字。为了便于讨论,我们假设这是一个函数:
# 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 03:49:09
创建另一个迭代器的itertools
解决方案:
from itertools import takewhile
l = takewhile(lambda x: x < 10000, generate())
如果您确定需要一个列表,请将其包装在list()
中:
l = list(takewhile(lambda x: x < 10000, generate()))
或者,如果你想要一个列表,比如发明轮子:
l = []
for x in generate():
if x < 10000:
l.append(x)
else:
break
发布于 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]
发布于 2013-02-02 08:00:55
itertools.takewhile
只有在遇到不满足谓词的项时才起作用。如果需要从可能的无序迭代器返回所有值,我建议使用Python2.x的itertools.ifilter
,如下所示
from itertools import ifilter
f = ifilter(lambda x: x < 400, gen())
f.next()
这过滤了一个生成器,如所希望的那样产生0到400之间的随机整数。
Python3.x中弃用了FWIW itertools.ifilter
,取而代之的是内置的filter()
,后者的迭代语法略有不同
f = filter(lambda x: x < 400, gen())
next(f)
https://stackoverflow.com/questions/14653870
复制相似问题