# 列表生成器-之生成器

2018/01/26 16:43

L = [x * x for x in range(10)]
print(L)

G = (x * x for x in range(10))
print(G)

[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
<generator object <genexpr> at 0x101c11f68>

G = (x * x for x in range(10))
for i in G:
print(i)输出：

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
fib(6)

1
1
2
3
5
8

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

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

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

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

for n in fib(6):
print(n)

### 小结

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

0
0 收藏

0 评论
0 收藏
0