zoukankan      html  css  js  c++  java
  • python_yield生成器

    1、先对比range 和 xrange 的区别

      >>> print range(10)

      [0123456789]

      >>> print xrange(10)

      xrange(10)

    如上代码所示,range会在内存中创建所有指定的数字,而xrange不会立即创建,只有在迭代循环时,才去创建每个数组。

    自定义生成器: 

    def func(arg):
    seed = 0
    while True:
    seed = seed +1
    if seed > arg:
    return
    else:
    yield seed

    for i in func(10):
    print i

    结果:1、2、3、4、5、6、7、8、9、10

    每到yield执行完,它会返回seed值,然后暂停执行,当再次循环调用它会从上次的暂停点再次执行至下次暂停或函数操作完成!


    2、文件操作的 read 和 xreadlinex 的的区别

    read会读取所有内容到内存
      xreadlines则只有在循环迭代时才获取
     
    基于next自定义生成器NReadlines:
    def NReadlines():
        with open('log','r') as f:
            while True:
                line = f.next()
                if line:
                    yield line
                else:
                    return
    
    for i in NReadlines():
        print i
    
    基于next自定义生成器NReadlines
    View Code
    基于seek和tell自定义生成器NReadlines:
    def NReadlines():
        with open('log','r') as f:
            seek = 0
            while True:
                f.seek(seek)
                data = f.readline()
                if data:
                    seek = f.tell()
                    yield data
                else:
                    return
    
    for item in NReadlines():
        print item
    
    基于seek和tell自定义生成器NReadlines
    View Code
     
     
     



  • 相关阅读:
    linux 中mysql的安装过程
    HashMap和Hashtable的区别
    SVN服务器配置(svn1.4.6+apache2.2.8 no ssl)
    ArrayList Vector LinkedList 区别与用法
    java中equals和==的区别
    flash滤镜
    AS3显示对象
    feathers ui 鼠标移出事件
    Flex 中可以应用于 ActionScript 类的元标签
    pureMVC与RobotLegs actionscript MVC框架对比
  • 原文地址:https://www.cnblogs.com/fengzaoye/p/5740857.html
Copyright © 2011-2022 走看看