# Python(9):迭代器和生成器

## 迭代器

### iter函数

``````# 1.iter

print('-------1.iter----------')
list = [1, 3, 4, 5, 53]
it = iter(list)
for x in it:
print(x, end=' ')
print('\n ')
``````

``````1 3 4 5 53
``````

### next函数

next()是取迭代器的数据，从第一个数据开始访问

``````print('-------2.next try except  stopIteration')
import sys   #引入 sys模块
list = [2, 3, 4, 87]
it = iter(list)

while True:
try:
print(next(it))
except StopIteration:
sys.exit()
``````

### 创建一个迭代器-自定义

``````class MyIteration:
def __iter__(self):
self.a = 1
return self

def __next__(self):
if self.a <= 20:
x = self.a
self.a += 1
return x
else:
raise StopIteration

return x

myclass = MyIteration()
myiter = iter(myclass)

print(next(myiter))
print(next(myiter))
print('---for 打印---')
for x in myiter:
print(x)
``````

``````-------3.创建一个迭代器---------
1
2
---for 打印---
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
``````

## 生成器

python中有个关键字yield是用来生成迭代器

``````print('-------4.yield生成器-------')
import sys

def fibonacci(n):  # 生成器函数 -斐波那契数列
a, b, count = 0, 1, 0
while True:
if (count > n):
return
yield a
a, b = b, a + b
count += 1

f = fibonacci(12)  # f是一个迭代器，由生成器生成
while True:
try:
print(next(f), end=' ')
except StopIteration:
sys.exit()

``````

``````-------4.yield生成器-------
0 1 1 2 3 5 8 13 21 34 55 89 144
``````