在一次面试中,面试官问我Python中使用的一些生成器。我知道生成器就像一个yield
值而不是return
的函数。
所以有人告诉我,for
/while
循环是生成器的一个例子。
最佳答案
简短回答:没有,但还有其他形式的生成器。
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 range(..)
、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()
关于python - 是来自 python 的 for/while 循环是一个生成器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44516289/