# Python 进阶_生成器 & 生成器表达式

2017-01-13 10:55:50来源:csdn作者:Jmilk人点击

Python 进阶_迭代器 & 列表解析

EXAMPLE：

In [94]: def fab(max):
...: n, a, b = 0, 0, 1
...: while n < max:
...: yield b
...: a, b = b, a + b
...: n = n + 1
...:In [95]: f = fab(5)In [96]: f.next()
Out[96]: 1In [97]: f.next()
Out[97]: 1In [98]: f.next()
Out[98]: 2In [99]: f.next()
Out[99]: 3In [100]: f.next()
Out[100]: 5In [101]: f.next()
---------------------------------------------------------------------------
StopIteration Traceback (most recent call last)
<ipython-input-101-c3e65e5362fb> in <module>()
----> 1 f.next()StopIteration:生成器 fab() 的执行过程

NOTE：而迭代器是不具有上述的特性的，不适合去处理一些巨大的类序列对象，所以建议优先考虑使用生成器来处理迭代的场景。

EXAMPLE 2：读取一个大文件

BLOCK_SIZE = 1024
with open(fpath, 'rb') as f:
while True:
if block:
yield block
else:
return

In [5]: def counter(start_at=0):
...: count = start_at
...: while True:
...: val = (yield count)
...: if val is not None:
...: count = val
...: else:
...: count += 1
...:In [6]: count = counter(5)In [7]: type(count)
Out[7]: generatorIn [8]: count.next()
Out[8]: 5In [9]: count.next()
Out[9]: 6In [10]: count.send(9) # 返回一个新的值给生成器中的 yield count
Out[10]: 9In [11]: count.next()
Out[11]: 10In [12]: count.close()# 关闭一个生成器In [13]: count.next()
---------------------------------------------------------------------------
StopIteration Traceback (most recent call last)
<ipython-input-13-3963aa0a181a> in <module>()
----> 1 count.next()StopIteration:生成器表达式

f = open('FILENAME', 'r')
longest = 0
while True:
if not linelen:
break
if linelen > longest:
longest = linelen
f.close()return longest

f = open('FILENAME', 'r')
longest = 0
f.close()
for line in allLines:
linelen = len(line.strip())
if not linelen:
break
if linelen > longest:
longest = linelenreturn longest

f = open('FILENAME', 'r')
longest = 0
allLines = [x.strip() for x in f.readlines()]
f.close()
for line in allLines:
linelen = len(line)
if not linelen:
break
if linelen > longest:
longest = linelenreturn longest

f = open('FILENAME', 'r')
allLinesLen = [line(x.strip()) for x in f]
f.close()
return max(allLinesLen) # 返回列表中最大的数值

f = open('FILENAME', 'r')
allLinesLen = (line(x.strip()) for x in f) # 这里的 x 相当于 yield x
f.close()
return max(allLinesLen)

f = open('FILENAME', 'r')
longest = max(line(x.strip()) for x in f)
f.close()
return longest

return max(line(x.strip()) for x in open('FILENAME'))小结