問題描述
迭代器和生成器有什么區(qū)別?關(guān)于何時(shí)使用每種情況的一些示例會(huì)很有幫助.
What is the difference between iterators and generators? Some examples for when you would use each case would be helpful.
推薦答案
iterator
是一個(gè)更籠統(tǒng)的概念:任何類具有 __next__
方法(Python 2 中的 next
) 和一個(gè) __iter__
方法,該方法執(zhí)行 return self
.
iterator
is a more general concept: any object whose class has a __next__
method (next
in Python 2) and an __iter__
method that does return self
.
每個(gè)生成器都是一個(gè)迭代器,但反之則不然.生成器是通過調(diào)用具有一個(gè)或多個(gè) yield
表達(dá)式(yield
語句,在 Python 2.5 及更早版本中)的函數(shù)來構(gòu)建的,并且是滿足上一段定義的對(duì)象迭代器
.
Every generator is an iterator, but not vice versa. A generator is built by calling a function that has one or more yield
expressions (yield
statements, in Python 2.5 and earlier), and is an object that meets the previous paragraph's definition of an iterator
.
當(dāng)您需要一個(gè)具有某種復(fù)雜的狀態(tài)維護(hù)行為的類,或者想要公開除 __next__
(和 __iter__
和 __init__
).大多數(shù)情況下,一個(gè)生成器(有時(shí),對(duì)于足夠簡單的需求,一個(gè)生成器表達(dá)式)就足夠了,而且它更容易編碼,因?yàn)闋顟B(tài)維護(hù)(在合理的范圍內(nèi))基本上是為你完成"的.由框架暫停和恢復(fù).
You may want to use a custom iterator, rather than a generator, when you need a class with somewhat complex state-maintaining behavior, or want to expose other methods besides __next__
(and __iter__
and __init__
). Most often, a generator (sometimes, for sufficiently simple needs, a generator expression) is sufficient, and it's simpler to code because state maintenance (within reasonable limits) is basically "done for you" by the frame getting suspended and resumed.
例如生成器如:
def squares(start, stop):
for i in range(start, stop):
yield i * i
generator = squares(a, b)
或等效的生成器表達(dá)式(genexp)
or the equivalent generator expression (genexp)
generator = (i*i for i in range(a, b))
需要更多代碼來構(gòu)建自定義迭代器:
would take more code to build as a custom iterator:
class Squares(object):
def __init__(self, start, stop):
self.start = start
self.stop = stop
def __iter__(self): return self
def __next__(self): # next in Python 2
if self.start >= self.stop:
raise StopIteration
current = self.start * self.start
self.start += 1
return current
iterator = Squares(a, b)
但是,當(dāng)然,使用類 Squares
您可以輕松地提供額外的方法,即
But, of course, with class Squares
you could easily offer extra methods, i.e.
def current(self):
return self.start
如果您對(duì)應(yīng)用程序中的此類額外功能有任何實(shí)際需求.
if you have any actual need for such extra functionality in your application.
這篇關(guān)于Python 的生成器和迭代器的區(qū)別的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!