zoukankan      html  css  js  c++  java
  • 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)
  • 相关阅读:
    开通博客
    实验一、命令解释程序的编写实验
    C#题目
    将Textbox、listview控件里的数据导入Excel
    unpV1的源码的使用方法
    git的基本使用方法(备忘)
    Shell中的exec和source解析(转载)
    无限式查找2013年2月28日
    解决"wxPython在Mac下的64位支持"的问题
    寻找固定的和2013年2月26日
  • 原文地址:https://www.cnblogs.com/wjc920/p/9256159.html
Copyright © 2011-2022 走看看