迭代器主要用于节省内存,迭代器可以迭代进行同样的操作。

比如迭代生成数据,那他就是一个数据容器,但是他是一个元素一个元素的生成,而不需要事先生成完整的序列,这就不需要很大的内存来存放这个序列,从而节省了内存。

 

迭代器是实现了__iter__和next方法的对象,iter返回迭代器自身,next读取下一个元素

 

创建迭代器

内建工厂函数-iter

i = iter('abc')
print(type(i))  # <type 'iterator'>
print i.next()  # 'a'
print i.next()  # 'b'
print i.next()  # 'c'
# i.next()
# Traceback (most recent call last):
# File "<string>", line 1, in <string>
# StopIteration:

读取完毕返回StopIteration

 

iter(func, sentinel)     如果是传递两个参数给 iter() , 它会重复地调用 func , 直到迭代器的下个值等于sentinel .func 是个迭代器

 

__iter__方法

i = list('abc').__iter__()
print(type(i))  # <type 'listiterator'>
print i.next()  # 'a'
print i.next()  # 'b'
print i.next()  # 'c'
i.next()
# StopIteration

 

手动创建

斐波那契数列

class Fib(object):
    def __init__(self):
        self.a, self.b = 0, 1   # 初始化两个计数器a,b

    def __iter__(self):
        return self             # 实例本身就是迭代对象,故返回自己

    def next(self):
        self.a, self.b = self.b, self.a + self.b        # 计算下一个值
        if self.a > 100000:                             # 退出循环的条件
            raise StopIteration()
        return self.a                                   # 返回下一个值          生成值

for n in Fib(): print n                                  # Fib()类返回迭代对象,for循环调用next方法
# 1 2 3 ...46368 75025

 

Python内置了一个模块itertools,包含了很多函数用于creating iterators for efficient looping(创建更有效率的循环迭代器)。

# encoding:utf-8
__author__ = 'HP'
### 生成无限序列
from itertools import count
counter = count(start=13)
print next(counter)             # 13
print next(counter)             # 14


### 从一个有限序列生成无限序列
from itertools import cycle
colors = cycle(['red', 'white', 'blue'])
print next(colors)              # 'red'
print next(colors)              # 'white'
print next(colors)              # 'blue'
print next(colors)              # 'red'


### 从无限序列中生成有限序列
from itertools import islice
colors = cycle(['red', 'white', 'blue'])  # infinite
limited = islice(colors, 0, 4)            # finite
for x in limited:
    print(x)
# red
# white
# blue
# red

具体请百度