有没有另一种方法在python生成器上调用next?

时间:2022-12-10 05:31:15

I have a generator and I would like to know if I can use it without having to worry about StopIteration , and I would like to use it without the for item in generator . I would like to use it with a while statement for example ( or other constructs ). How could I do that ?

我有一个发电机,我想知道我是否可以使用它而不必担心StopIteration,我想在没有发电机的for项目的情况下使用它。我想将它与while语句(或其他构造)一起使用。我怎么能这样做?

3 个解决方案

#1


-1  

Use this to wrap your generator:

用它来包裹你的发电机:

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.

Use it like this:

像这样用它:

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

Update: Please use the answer below because it is much better than this one.

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

#2


15  

built-in function

内置功能

next(iterator[, default])
Retrieve the next item from the iterator by calling its __next__() method. If default is given, it is returned if the iterator is exhausted, otherwise StopIteration is raised.

next(iterator [,default])通过调用__next __()方法从迭代器中检索下一个项目。如果给定default,则在迭代器耗尽时返回,否则引发StopIteration。

In Python 2.5 and older:

在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

#3


1  

Another options is to read all generator values at once:

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

>>> alist = list(agenerator)

Example:

例:

>>> def f():
...   yield 'a'
...
>>> a = list(f())
>>> a[0]
'a'
>>> len(a)
1

#1


-1  

Use this to wrap your generator:

用它来包裹你的发电机:

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.

Use it like this:

像这样用它:

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

Update: Please use the answer below because it is much better than this one.

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

#2


15  

built-in function

内置功能

next(iterator[, default])
Retrieve the next item from the iterator by calling its __next__() method. If default is given, it is returned if the iterator is exhausted, otherwise StopIteration is raised.

next(iterator [,default])通过调用__next __()方法从迭代器中检索下一个项目。如果给定default,则在迭代器耗尽时返回,否则引发StopIteration。

In Python 2.5 and older:

在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

#3


1  

Another options is to read all generator values at once:

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

>>> alist = list(agenerator)

Example:

例:

>>> def f():
...   yield 'a'
...
>>> a = list(f())
>>> a[0]
'a'
>>> len(a)
1