3

有没有一种更 Pythonic 的方式,或者至少是一种更短更简单的方式来做到这一点:

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

3 回答 3

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
于 2012-05-28T13:14:13.960 回答
3

无需进入itertools...

i = 1
res = lookup(i)
while res is not None:
    i += 1
    yield res
    res = lookup(i)
于 2012-05-28T13:16:23.743 回答
3

itertools.count可以无限计数:

for i in itertools.count(1):
    res = lookup(i)
    if res is None: break
    yield res
于 2012-05-28T13:22:09.557 回答