Python生成器表达式

简介:

  生成器表达式并不真正的创建数字列表,而是返回一个生成器对象,此对象在每次计算出一个条目后,把这个条目"产生"(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'
http://www.cnblogs.com/spiritman/
原文地址:https://www.cnblogs.com/spiritman/p/5159876.html