简答:不,但还有其他形式的发电机.
for / while循环是一个循环结构:它不发出值,因此不是生成器.
然而,还有其他方法来构建生成器.
例如,yield就是例如一个生成器:
def some_generator(xs):
for x in xs:
if x:
yield x
但也有生成器表达式,如:
(x for x in xs if x)
此外,在python-3.x中,范围(..),map(..),filter(..)构造也是生成器.
当然,您可以进行迭代(通过使用可迭代模式):
class some_generator(object):
def __init__(self, xs):
self.n = n
self.idx = 0
def __iter__(self):
return self
def __next__(self):
return self.next()
def next(self):
while self.num < len(self.xs) and not self.xs[self.num]:
self.num += 1
if self.num < len(self.xs):
res = self.xs[self.num]
self.num += 1
return res
else:
raise StopIteration()