# Python 发生器

2020年6月25日 2018年7月22日

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
``````