python 学习笔记6 生成器

a, b = b, a + b这句话意思是 把b赋给a，把a+b赋给b

>>> L = [x * x for x in range(10)]
>>> L
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
>>> g = (x * x for x in range(10))
>>> g
<generator object <genexpr> at 0x1022ef630>


>>> next(g)
0
>>> next(g)
1
>>> next(g)
4
>>> next(g)
9
>>> next(g)
16
>>> next(g)
25
>>> next(g)
36
>>> next(g)
49
>>> next(g)
64
>>> next(g)
81
>>> next(g)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
StopIteration


>>> g = (x * x for x in range(10))
>>> for n in g:
...     print(n)
...
0
1
4
9
16
25
36
49
64
81


generator非常强大。如果推算的算法比较复杂，用类似列表生成式的for循环无法实现的时候，还可以用函数来实现。

1, 1, 2, 3, 5, 8, 13, 21, 34, ...

def fib(max):
n, a, b = 0, 0, 1
while n < max:
print(b)
a, b = b, a + b
n = n + 1
return 'done'


>>> fib(6)
1
1
2
3
5
8
'done'


def fib(max):
n, a, b = 0, 0, 1
while n < max:
yield b
a, b = b, a + b
n = n + 1
return 'done'


>>> f = fib(6)
>>> f
<generator object fib at 0x104feaaa0>


def odd():
print('step 1')
yield 1
print('step 2')
yield(3)
print('step 3')
yield(5)


>>> o = odd()
>>> next(o)
step 1
1
>>> next(o)
step 2
3
>>> next(o)
step 3
5
>>> next(o)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
StopIteration


>>> for n in fib(6):
...     print(n)
...
1
1
2
3
5
8


>>> g = fib(6)
>>> while True:
...     try:
...         x = next(g)
...         print('g:', x)
...     except StopIteration as e:
...         print('Generator return value:', e.value)
...         break
...
g: 1
g: 1
g: 2
g: 3
g: 5
g: 8
Generator return value: done


练习

          1
1   1
1   2   1
1   3   3   1
1   4   6   4   1
1   5   10  10  5   1


小结

generator是非常强大的工具，在Python中，可以简单地把列表生成式改成generator，也可以通过函数实现复杂逻辑的generator。

>>> r = abs(6)
>>> r
6


generator函数的“调用”实际返回一个generator对象：

>>> g = fib(6)
>>> g
<generator object fib at 0x1022ef948>

• 本文已收录于以下专栏：

举报原因： 您举报文章：python 学习笔记6 生成器 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)