for(i = 0; True; i ++)在python中?

时间:2012-05-28 13:09:50

标签: python

是否有更多的pythonic方式,或者至少更短更简单的方法来执行此操作:

i = 1
while True:
    res = lookup(i) # returns a value or None
    if res is None:
        break
    else:
        i += 1
        yield res

3 个答案:

答案 0 :(得分:7)

您可以使用itertools

from itertools import takewhile, count

# ...
def myfunc():
    return takewhile(lambda x: x is not None, (lookup(i) for i in count(1)))

如果您因任何原因不喜欢takewhile

for i in count(1):
     res = lookup(i)
     if res is None: break
     yield res

答案 1 :(得分:3)

不进入itertools ...

i = 1
res = lookup(i)
while res is not None:
    i += 1
    yield res
    res = lookup(i)

答案 2 :(得分:3)

itertools.count可以无限期地计算:

for i in itertools.count(1):
    res = lookup(i)
    if res is None: break
    yield res