# Python 發生器

Jinku Hu 2023年1月30日

Python 發生器是一種惰性迭代器，它通過發生器函式（使用 `yield` 關鍵字）來建立，或者通過發生器表示式（比如 `an_expression for x in an_iterator `）。

## 介紹

``````expressionEg = (x ** 2 for x in range(10))
``````

``````def function():
for x in range(10):
yield x ** 2
``````

Info

``````sum(i for i in range(10) if i % 2 == 0)  # Output: 20
any(x == 0 for x in foo)  # Output: True or False depending on foo
type(a > b for a in foo if a % 2 == 1)  # Output: <class 'generator'>
``````

``````sum((i for i in range(10) if i % 2 == 0))
any((x == 0 for x in foo))
type((a > b for a in foo if a % 2 == 1))
``````

``````g1 = function()
print(g1)  # Out: <generator object function at 0x1012e1888>
``````

``````for x in g1:

# Output

arr1 = list(g1)
# arr1 = [], 因為上面的迴圈已經把所有的資料給用光了
g2 = function()
arr2 = list(g2)  # arr2 = [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
``````

``````g3 = function()
a = next(g3)  # a becomes 0
b = next(g3)  # b becomes 1
c = next(g3)  # c becomes 2
...
j = next(g3)  # Raises StopIteration, j remains undefined
``````

## 迭代

``````# 簡單的 Python 2.x 中 xrange()函式的實現
def xrange(n):
i = 0
while i < n:
yield i
i += 1

# 迴圈
for i in xrange(10):
print(i)  # prints the values 0, 1, ..., 9

# unpacking
a, b, c = xrange(3)  # 0, 1, 2

# building a list
l = list(xrange(10))  # [0, 1, ..., 9]
``````

## `next()` 函式

``````def nums():
yield 1
yield 2
yield 3

generator = nums()

next(generator, None)  # 1
next(generator, None)  # 2
next(generator, None)  # 3
next(generator, None)  # None
next(generator, None)  # None
# .
``````

## 生成器表示式

``````generator = (i * 2 for i in range(3))

next(generator)  # 0
next(generator)  # 2
next(generator)  # 4
next(generator)  # raises StopIteration
``````

``````sum(i ** 2 for i in range(4))  # 0^2 + 1^2 + 2^2 + 3^2 = 0 + 1 + 4 + 9 = 14
``````

DelftStack.com 創辦人。Jinku 在機器人和汽車行業工作了8多年。他在自動測試、遠端測試及從耐久性測試中創建報告時磨練了自己的程式設計技能。他擁有電氣/ 電子工程背景，但他也擴展了自己的興趣到嵌入式電子、嵌入式程式設計以及前端和後端程式設計。