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

  • 相关阅读:
    spring IOC --- 控制反转(依赖注入)----简单的实例
    Spring MVC 返回视图时添加的模型数据------POJO
    Controller接口控制器3
    Controller接口控制器2
    Controller接口控制器
    Spring-MVC:应用上下文webApplicationContext
    DispatcherServlet 前置控制器
    WEB安全 asp+access注入
    WEB安全 Sqlmap 中绕过空格拦截的12个脚本
    Python 爬虫练习(三) 利用百度进行子域名收集
  • 原文地址:https://www.cnblogs.com/alben-cisco/p/6896926.html
Copyright © 2011-2022 走看看