is there an alternative way of calling next on python generators?

可紊 提交于 2019-12-22 11:01:12

问题


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 ?


回答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:


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.

In Python 2.5 and older:

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:


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


来源:https://stackoverflow.com/questions/500578/is-there-an-alternative-way-of-calling-next-on-python-generators

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!