Python 中迭代器和生成器的區別

Jesse John 2023年1月30日

Python 中的迭代器

1. 迭代器是使用實現迭代器協議的類建立的物件。這意味著該類定義了 `__iter__``__next__` 方法。
2. `__next__` 方法使用 `return` 語句返回一個值。由於 `return` 語句必須是該方法的最後一行，我們必須在 `return` 語句之前更新要在 `__next__` 下一次執行中使用的變數。

Python 中的生成器

1. 生成器是一個函式。
2. 生成器函式使用 `yield` 關鍵字而不是 `return` 關鍵字。
2.1 `yield` 關鍵字產生一個值並暫停函式的執行。
2.2 對 `next()` 的下一次呼叫在 `yield` 語句之後恢復程式碼的執行。

Python 中的迭代器和生成器示例

``````# ITERATOR (Class)

class squares(object):
def __init__(self, num1):
self.nxt_sq_of = 1
self.lim = num1

def __iter__(self):
return self

def __next__(self):

if self.nxt_sq_of <= self.lim:
ret_sq_of = self.nxt_sq_of
self.nxt_sq_of += 1
return ret_sq_of * ret_sq_of
else:
raise StopIteration

# Iterator Object
a = squares(6)

# Next value of the iterator.
next(a)
next(a)
next(a)
next(a)
next(a)
next(a)
next(a)
next(a)

# Using the iterator in a loop.
a1 = squares(6)

while True:
print(next(a1))
``````

``````next(a)
Out[3]: 1

next(a)
Out[4]: 4

next(a)
Out[5]: 9

next(a)
Out[6]: 16

next(a)
Out[7]: 25

next(a)
Out[8]: 36

next(a)
Traceback (most recent call last):

File "<ipython-input-9-15841f3f11d4>", line 1, in <module>
next(a)

File "<ipython-input-1-9dbe8e565876>", line 17, in __next__
raise StopIteration

StopIteration
``````

``````# GENERATOR FUNCTION

def gen_squares(num2):
i = 1
while i <= num2:
yield i * i
i += 1

# Generator iterator.
b = gen_squares(5)

# Next yield of the generator iterator.
next(b)
next(b)
next(b)
next(b)
next(b)
next(b)
``````

``````next(b)
Out[3]: 1

next(b)
Out[4]: 4

next(b)
Out[5]: 9

next(b)
Out[6]: 16

next(b)
Out[7]: 25

next(b)
Traceback (most recent call last):

File "<ipython-input-8-adb3e17b0219>", line 1, in <module>
next(b)

StopIteration
``````

まとめ

1. 生成器的 Python Wiki 文章。
2. 迭代器的 Python Wiki 文章。

Jesse is passionate about data analysis and visualization. He uses the R statistical programming language for all aspects of his work.