# 四、生成器

## 2、生成器的创建

``````# -*- coding: UTF-8 -*-
gen= (x * x for x in range(10))
print(gen)
``````

`````` at 0x0000000002734A40>
``````

## 3、遍历生成器的元素

``````# -*- coding: UTF-8 -*-
gen= (x * x for x in range(10))

for num  in  gen :
print(num)
``````

## 4、以函数的形式实现生成器

``````# -*- coding: UTF-8 -*-
def my_function():
for i in range(10):
print ( i )

my_function()
``````

``````0
1
2
3
4
5
6
7
8
9
``````

``````# -*- coding: UTF-8 -*-
def my_function():
for i in range(10):
yield i

print(my_function())
``````

``````
``````

``````# -*- coding: UTF-8 -*-
def fibon(n):
a = b = 1
for i in range(n):
yield a
a, b = b, a + b

# 引用函数
for x in fibon(1000000):
print(x , end = ' ')
``````

``````# -*- coding: UTF-8 -*-
def odd():
print ( 'step 1' )
yield ( 1 )
print ( 'step 2' )
yield ( 3 )
print ( 'step 3' )
yield ( 5 )

o = odd()
print( next( o ) )
print( next( o ) )
print( next( o ) )
``````

``````step 1
1
step 2
3
step 3
5
``````

## 5、打印杨辉三角

``````# -*- coding: UTF-8 -*-
def triangles( n ):         # 杨辉三角形
L = [1]
while True:
yield L
L.append(0)
L = [ L [ i -1 ] + L [ i ] for i in range (len(L))]

n= 0
for t in triangles( 10 ):   # 直接修改函数名即可运行
print(t)
n = n + 1
if n == 10:
break
``````

``````[1]
[1, 1]
[1, 2, 1]
[1, 3, 3, 1]
[1, 4, 6, 4, 1]
[1, 5, 10, 10, 5, 1]
[1, 6, 15, 20, 15, 6, 1]
[1, 7, 21, 35, 35, 21, 7, 1]
[1, 8, 28, 56, 70, 56, 28, 8, 1]
[1, 9, 36, 84, 126, 126, 84, 36, 9, 1]
``````