4

我有一个生成器,我想知道是否可以使用它而不必担心 StopIteration ,我想在没有for item in generator. 例如,我想将它与 while 语句(或其他构造)一起使用。我怎么能那样做?

4

3 回答 3

15

内置函数

next(iterator[, default])
通过调用迭代器的方法从迭代器中检索下一项__next__() 。如果给出默认值,则在迭代器耗尽时返回,否则引发 StopIteration。

在 Python 2.5 及更早版本中:

raiseStopIteration = object()
def next(iterator, default=raiseStopIteration):
    if not hasattr(iterator, 'next'):
       raise TypeError("not an iterator")
    try:
       return iterator.next()
    except StopIteration:
        if default is raiseStopIteration:
           raise
        else:
           return default
于 2009-02-01T11:12:53.937 回答
2

另一种选择是一次读取所有生成器值:

>>> alist = list(agenerator)

例子:

>>> def f():
...   yield 'a'
...
>>> a = list(f())
>>> a[0]
'a'
>>> len(a)
1
于 2009-02-01T12:16:35.897 回答
-1

使用它来包装你的生成器:

class GeneratorWrap(object):

      def __init__(self, generator):
          self.generator = generator

      def __iter__(self):
          return self

      def next(self):
          for o in self.generator:
              return o
          raise StopIteration # If you don't care about the iterator protocol, remove this line and the __iter__ method.

像这样使用它:

def example_generator():
    for i in [1,2,3,4,5]:
        yield i

gen = GeneratorWrap(example_generator())
print gen.next()  # prints 1
print gen.next()  # prints 2

更新:请使用下面的答案,因为它比这个要好得多。

于 2009-02-01T11:13:09.177 回答