• 5.python数据结构-迭代器(iterator)&生成器(generator)


    # 迭代器(Iterator)&生成器(generator)
    # 若要对象可迭代:
    # 在python2中对象必须包含__iter__(self)和next(self)
    # 在python3中对象必须包含__iter__(self)和__next__(self)
    # 其中:__iter__(self)必须返回一个含有含有__next__(self)的对象,
    #     可以是自身(见SimpleCounter),也可以其他对象(见SimpleCounter1)
    
    
    # 创建一个迭代器
    class SimpleCounter(object):
        def __init__(self, start, end):
            self.start = start
            self.current = self.start
            self.end = end
    
        def __iter__(self):
            return self
    
        # 如果是python2这里用next,python用__next__
        def __next__(self):
            if self.current > self.end:
                raise StopIteration
            else:
                self.current += 1
                return self.current - 1
    
    
    class SimpleCounter1(object):
        def __init__(self, start, end):
            self.start = start
            self.current = self.start
            self.end = end
    
        def __iter__(self):
            return SimpleCounter(self.start, self.end)
    
        # 该类中该函数可要可不要
        # 如果是python2这里用next,python用__next__
        def __next__(self):
            if self.current > self.end:
                self.current = self.start
                raise StopIteration
            else:
                self.current += 1
                return self.current - 1
    
    
    # 访问迭代器
    simple_counter = SimpleCounter(1, 4)
    
    print('first traversal simple_counter:')
    for x in simple_counter:
        print(x)
    # output:
    # 1
    # 2
    # 3
    # 4
    
    # 第二次迭代没有结果,因为迭代器只能被遍历一次
    print('second traversal simple_counter:')
    for x in simple_counter:
        print(x)
    
    simple_counter1 = SimpleCounter1(1, 4)
    print('traversal simple_counter1...')
    for x in simple_counter1:
        print(x)
    
    # 使用生成器生成一个迭代器,b为迭代器对象,(x ** 2 for x in a)为生成器
    a = [0, 1, 2, 3, 4]
    b = (x ** 2 for x in a)
    
    print('traverse the iterator created by one generator for the first time:')
    for x in b:
        print(x);
    print('traverse the iterator created by one generator for the second time:')
    # 本次遍历没有结果,因为b是迭代器
    for x in b:
        print(x);
    
    注:
    -python玩转数据科学之准备数据(使用到generator)
  • 相关阅读:
    request.getDispatcher().forward(request,response)和response.sendRedirect()的区别
    处理get中文乱码
    在oracle里,如何取得本周、本月、本季度、本年度的第一天和最后一天的时间
    js 获取 本周、上周、本月、上月、本季度、上季度的开始结束日期
    Oracle 查询今天、昨日、本周、本月和本季度的所有记录
    CASE WHEN 及 SELECT CASE WHEN的用法
    漳州台的八边形坐标
    ubuntu16.04下下载baiduyun大文件
    ubuntu16.04下gmt5.4.1 中文支持
    ubuntu16.04下wps的安装
  • 原文地址:https://www.cnblogs.com/wjc920/p/9256159.html
Copyright © 2020-2023  润新知