是否有一种简单的方法来测试生成器是否没有项目,比如peek, hasNext, isEmpty之类的?


当前回答

刚刚读到这篇文章,意识到缺少一个非常简单易懂的答案:

def is_empty(generator):
    for item in generator:
        return False
    return True

如果我们不打算使用任何项,那么我们需要将第一项重新注入生成器:

def is_empty_no_side_effects(generator):
    try:
        item = next(generator)
        def my_generator():
            yield item
            yield from generator
        return my_generator(), False
    except StopIteration:
        return (_ for _ in []), True

例子:

>>> g=(i for i in [])
>>> g,empty=is_empty_no_side_effects(g)
>>> empty
True
>>> g=(i for i in range(10))
>>> g,empty=is_empty_no_side_effects(g)
>>> empty
False
>>> list(g)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

其他回答

使用cytoolz中的peek函数。

from cytoolz import peek
from typing import Tuple, Iterable

def is_empty_iterator(g: Iterable) -> Tuple[Iterable, bool]:
    try:
        _, g = peek(g)
        return g, False
    except StopIteration:
        return g, True

此函数返回的迭代器将等效于作为参数传入的原始迭代器。

对你的问题的简单回答是:不,没有简单的方法。有很多变通办法。

不应该有一种简单的方法,因为生成器是一种输出值序列而不将序列保存在内存中的方法。所以没有向后遍历。

你可以写一个has_next函数,或者甚至可以把它作为一个带有花哨装饰器的方法放在生成器上。

Quick-dirty解决方案:

next(generator, None)不是None

或者将None替换为任何你知道不在生成器中的值。

编辑:是的,这将跳过生成器中的一项。然而,有时我只是出于验证目的检查生成器是否为空,然后并不真正使用它。否则我就会这样做:

def foo(self):
    if next(self.my_generator(), None) is None:
        raise Exception("Not initiated")

    for x in self.my_generator():
        ...

也就是说,如果您的生成器来自一个函数,如my_generator(),则此方法有效。

恕我直言,最好的办法是避免特殊测试。大多数时候,使用生成器是一种测试:

thing_generated = False

# Nothing is lost here. if nothing is generated, 
# the for block is not executed. Often, that's the only check
# you need to do. This can be done in the course of doing
# the work you wanted to do anyway on the generated output.
for thing in my_generator():
    thing_generated = True
    do_work(thing)

如果这还不够好,您仍然可以执行显式测试。此时,thing将包含最后生成的值。如果没有生成任何内容,它将是未定义的—除非您已经定义了该变量。你可以检查东西的价值,但那有点不可靠。相反,只需在块内设置一个标志,然后检查它:

if not thing_generated:
    print "Avast, ye scurvy dog!"

对于这种显而易见的方法,我很抱歉,但最好的方法是:

for item in my_generator:
     print item

现在您已经检测到在使用生成器时它是空的。当然,如果生成器为空,项将永远不会显示。

这可能不完全适合您的代码,但这就是生成器的习惯用法:迭代,所以您可能会稍微改变您的方法,或者根本不使用生成器。