迭代器, 生成器

iterator(迭代器):

任何实现了  __ iter__  和  __ next__  (python2中实现next()) 方法的对象都是迭代器.

__ iter__  返回迭代器自身

__ next__  返回容器中的下一个值
 
 如果容器中没有更多元素,则抛出StopIteration异常

generator(生成器):

生成器其实是一种特殊的迭代器, 不需要自定义  __ iter__  和  __ next__

  • 生成器函数 (yield)
  • 生成器表达式

迭代器、生成器有什么好处?

  • 节省内存
  • 惰性求值

练习1: 自定义一个迭代器, 实现斐波那契数列

In [36]: class Fib(object):
    ...:     def __init__(self, max):
    ...:         self.x = 0
    ...:         self.y = 1
    ...:         self.max = max
    ...:

In [37]: class Fib(object):
    ...:     def __init__(self, max):
    ...:         self.x = 0
    ...:         self.y = 1
    ...:         self.max = max
    ...:     def __iter__(self):
    ...:         return self
    ...:     def __next__(self):
    ...:         n_next = self.y
    ...:         self.x, self.y = self.y, self.x + self.y
    ...:         if self.max >self.x:
    ...:             return n_next
    ...:         else:
    ...:             raise StopIteration()
    ...:

In [38]: a = Fib(5)

In [39]: for i in a:
    ...:     print(i)

自定义一个生成器函数, 实现斐波那契数列

def fib(max):
    x = 0
    y = 1
    while y < max:
        yield y
        x, y = y, x+y

练习3: 定义一个随机数迭代器, 随机范围为 [1, 50], 最大迭代次数 30

import random

a = random.randrange(1,51)
        
        
class Ran:
    def __init__(self):
        self.max = 30
        self.x = 0
        
    def __iter__(self):
        return self
    
    def __next__(self):
        self.x += 1
        if self.x <self.max:
            return random.randrange(1,51)
        else:
            raise StopIteration
            
        
posted @ 2018-07-18 15:00  数据菜鸟  阅读(287)  评论(0)    收藏  举报