zoukankan      html  css  js  c++  java
  • 迭代器与生成器

    迭代器(iterator

    迭代器是访问集合元素的一种方式。迭代器对象从集合的第一个元素开始访问,直到所有的元素被访问完结束。迭代器只能往前不会后退,迭代器不要求所有元素实现存在,

    只有当迭代到某个元素的时候才使用该元素,这一个特性非常适用于处理超大规模集合或者几个G的文件。

    特点:

    1. 访问者不需要关心迭代器内部的结构,仅需通过__next__()方法不断去取下一个内容
    2. 不能随机访问集合中的某个值 ,只能从头到尾依次访问
    3. 访问到一半时不能往回退
    4. 便于循环比较大的数据集合,节省内存(Linux的cat就是使用了迭代)

    生成一个迭代器

    1 names = iter(['alex','alben','jack'])
    2 print(type(names))
    3 
    4 print(names.__next__())
    5 print(names.__next__())
    6 print(names.__next__())

    在迭代的过程中,可以继续给列表添加元素,已提供后续的迭代。

    生成器(generator)

    一个函数调用时,返回一个迭代器(iterator)这个函数就是一个生成器,在函数中包含语法yield就是定义一个生成器。

    案例:

    import sys
    def read_file(file):
        with open(file) as f:
            for line in f:
                print(line.strip())
                yield
    
    
    cat = read_file('ethernet.txt')
    print("逐行读取文件内容,请根据需求退出")
    
    while True:
        choose = input("Enter no to exit from the process: ")
        if choose.upper() == 'NO':
            exit()
        else :
            cat.__next__()
    View Code

    效果:

    逐行读取文件内容,请根据需求退出
    Enter no to exit from the process:
    0x0000 - 0x05DC IEEE 802.3 长度
    Enter no to exit from the process:
    0x0101 – 0x01FF 实验
    Enter no to exit from the process:
    0x0600 XEROX NS IDP
    Enter no to exit from the process:
    0x0660
    Enter no to exit from the process: no

    Process finished with exit code 0

  • 相关阅读:
    ES6 Symbol类型 附带:Proxy和Set
    why updating the Real DOM is slow, what is Virtaul DOM, and how updating Virtual DOM increase the performance?
    React高级指南
    池(Pool)
    计算机网络Intro
    React基础
    CommonJS 与 ES6 的依赖操作方法(require、import)
    webpack初识(biaoyansu)
    关于时间安排贪心算法正确性的证明
    DP总结
  • 原文地址:https://www.cnblogs.com/alben-cisco/p/6896926.html
Copyright © 2011-2022 走看看