問題描述
迭代器和生成器有什么區別?關于何時使用每種情況的一些示例會很有幫助.
What is the difference between iterators and generators? Some examples for when you would use each case would be helpful.
推薦答案
iterator
是一個更籠統的概念:任何類具有 __next__
方法(Python 2 中的 next
) 和一個 __iter__
方法,該方法執行 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
.
每個生成器都是一個迭代器,但反之則不然.生成器是通過調用具有一個或多個 yield
表達式(yield
語句,在 Python 2.5 及更早版本中)的函數來構建的,并且是滿足上一段定義的對象迭代器
.
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
.
當您需要一個具有某種復雜的狀態維護行為的類,或者想要公開除 __next__
(和 __iter__
和 __init__
).大多數情況下,一個生成器(有時,對于足夠簡單的需求,一個生成器表達式)就足夠了,而且它更容易編碼,因為狀態維護(在合理的范圍內)基本上是為你完成"的.由框架暫停和恢復.
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)
或等效的生成器表達式(genexp)
or the equivalent generator expression (genexp)
generator = (i*i for i in range(a, b))
需要更多代碼來構建自定義迭代器:
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)
但是,當然,使用類 Squares
您可以輕松地提供額外的方法,即
But, of course, with class Squares
you could easily offer extra methods, i.e.
def current(self):
return self.start
如果您對應用程序中的此類額外功能有任何實際需求.
if you have any actual need for such extra functionality in your application.
這篇關于Python 的生成器和迭代器的區別的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!