# 本文以实例详解了python的迭代器与生成器，具体如下所示：

## 迭代器概述：

### 迭代器的优点

next方法：返回迭代器的下一个元素iter方法：返回迭代器对象本身 下面用生成斐波那契数列为例子，说明为何用迭代器

```def fab(max):
n, a, b = 0, 0, 1
while n < max:
print b
a, b = b, a + b
n = n + 1```

```def fab(max):
L = []
n, a, b = 0, 0, 1
while n < max:
L.append(b)
a, b = b, a + b
n = n + 1
return L```

```for i in range(1000): pass
for i in xrange(1000): pass```

```class Fab(object):
def __init__(self, max):
self.max = max
self.n, self.a, self.b = 0, 0, 1

def __iter__(self):
return self

def next(self):
if self.n < self.max:
r = self.b
self.a, self.b = self.b, self.a + self.b
self.n = self.n + 1
return r
raise StopIteration()```

```>>> for key in Fabs(5):
print key```

Fabs 类通过 next() 不断返回数列的下一个数，内存占用始终为常数

### 使用迭代器

```>>> lst = range(5)
>>> it = iter(lst)
>>> it
<listiterator object at 0x01A63110>```

```>>> it.next()

>>> it.next()

>>> it.next()```

python处理迭代器越界是抛出StopIteration异常

```>>> it.next()

>>> it.next

<method-wrapper 'next' of listiterator object at 0x01A63110>
>>> it.next()

>>> it.next()

Traceback (most recent call last):
File "<pyshell#27>", line 1, in <module>
it.next()
StopIteration```

```lst = range(5)
it = iter(lst)
try:
while True:
val = it.next()
print val
except StopIteration:
pass```

```>>> a = (1, 2, 3, 4)
>>> for key in a:
print key```

### 定义迭代器

```# -*- coding: cp936 -*-
class Fabs(object):
def __init__(self,max):
self.max = max
self.n, self.a, self.b = 0, 0, 1 #特别指出：第0项是0，第1项是第一个1.整个数列从1开始
def __iter__(self):
return self
def next(self):
if self.n < self.max:
r = self.b
self.a, self.b = self.b, self.a + self.b
self.n = self.n + 1
return r
raise StopIteration()

print Fabs(5)
for key in Fabs(5):
print key```

`<__main__.Fabs object at 0x01A63090>`

## 生成器

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

```>>> for n in fab(5):
print n```

```>>> f = fab(3)
>>> f.next()
1
>>> f.next()
1
>>> f.next()
2
>>> f.next()

Traceback (most recent call last):
File "<pyshell#62>", line 1, in <module>
f.next()
StopIteration```

return的作用

```>>> s = fab(5)
>>> s.next()
1
>>> s.next()

Traceback (most recent call last):
File "<pyshell#66>", line 1, in <module>
s.next()
StopIteration```

```def read_file(fpath):
BLOCK_SIZE = 1024
with open(fpath, 'rb') as f:
while True:
if block:
yield block
else:
return```

15 篇文章31 人订阅

0 条评论

## 相关文章

2967

3379

### 【选择题】Java基础测试四（15道）

【选择题】Java基础测试四（15道） 41.以下哪项是接口的正确定义？（ B D ） A、 interface B { void print...

4889

924

### 正则表达式30分钟入门教程

30分钟内让你明白正则表达式是什么，并对它有一些基本的了解，让你可以在自己的程序或网页里使用它。

550

1315

6112

5166

4027

2822