【发布时间】:2010-10-04 18:35:56
【问题描述】:
我有一个生成器,我想知道是否可以使用它而不必担心 StopIteration ,我想在没有 for item in generator 的情况下使用它。例如,我想将它与 while 语句(或其他构造)一起使用。我怎么能这样做?
【问题讨论】:
我有一个生成器,我想知道是否可以使用它而不必担心 StopIteration ,我想在没有 for item in generator 的情况下使用它。例如,我想将它与 while 语句(或其他构造)一起使用。我怎么能这样做?
【问题讨论】:
用它来包装你的生成器:
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
更新:请使用下面的答案,因为它比这个更好。
【讨论】:
next 名称。叫它别的东西,例如safe_next(self, sentinel=None) 方法 -- 返回 sentinel 而不是抛出 StopIteration。内置next() 功能不同。
next_noraise()。更好的是使用@SilentGhost 的建议。
另一种选择是一次读取所有生成器值:
>>> alist = list(agenerator)
例子:
>>> def f():
... yield 'a'
...
>>> a = list(f())
>>> a[0]
'a'
>>> len(a)
1
【讨论】:
for 循环的情况下使用。它可以与while 循环一起使用。问题中的所有条件均已满足。
内置函数
下一个(迭代器[,默认])
通过调用__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
【讨论】:
next() 实现