• Python生成器表达式


    作者博文地址:https://www.cnblogs.com/liu-shuai/

    简介:

      生成器表达式并不真正的创建数字列表,而是返回一个生成器对象,此对象在每次计算出一个条目后,把这个条目"产生"(yield)出来。生成器表达式使用了"惰性计算"或称作"延时求值"的机制。

      序列过长,并且每次只需要获取一个元素时,应该考虑生成器表达式而不是列表解析。

    语法:

      (expression for iter_val in iterable)

      (expression for iter_val in iterable if cond_expr)

    实例展示:

     1 >>> N = (i**2 for i in range(1,11))
     2 >>> print N
     3 <generator object <genexpr> at 0x7fe4fd0e1c30>      #此处返回的是一个生成器的地址
     4 >>> N.next()
     5 1
     6 >>> N.next()
     7 4
     8 >>> N.next()
     9 9
    10 >>> N.next()
    11 16
    12 >>> N.next()
    13 25
    14 >>> N.next()
    15 36
    16 >>> N.next()
    17 49
    18 >>> N.next()
    19 64
    20 >>> N.next()
    21 81
    22 >>> N.next()
    23 100
    24 >>> N.next()                #所有元素遍历完后,抛出异常
    25 Traceback (most recent call last):
    26   File "<stdin>", line 1, in <module>
    27 StopIteration    
     1 >>> import os
     2 >>> F = (file for file in os.listdir('/var/log') if file.endswith('.log'))
     3 >>> print F
     4 <generator object <genexpr> at 0x7fe4fd0e1c80>
     5 >>> F.next()
     6 'anaconda.ifcfg.log'
     7 >>> F.next()
     8 'Xorg.0.log'
     9 >>> F.next()
    10 'anaconda.storage.log'
    11 >>> F.next()
    12 'Xorg.9.log'
    13 >>> F.next()
    14 'yum.log'
  • 相关阅读:
    设计模式之策略模式
    整理Java面向对象
    springboot+easyui+jpa实现动态权限角色的后台管理系统(二)
    随笔9
    随笔8
    随笔7
    PHP curl方法集合
    curl json方式提交
    富文本图片和视频标签增加域名前缀
    fastadmin原生编辑按钮点击默认100%显示
  • 原文地址:https://www.cnblogs.com/liu-shuai/p/6098218.html
Copyright © 2020-2023  润新知