作者博文地址: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'
