• 发表于 2年前
• 阅读 65
• 收藏 2
• 评论 0

# 黄哥漫谈Python 生成器

for 循环 没有输出。

PEP 342 -- Coroutines via Enhanced Generators

https://www.python.org/dev/peps/pep-0342/

## 下面讲讲生成器实例代码。

1、利用生成器生成可以无限取值的斐波拉切函数。

``````	#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author: 黄哥python培训 qq:1465376564

def fib():
a, b = 0, 1
while True:
yield a
a, b = b, a + b

p = fib()
print [p.next() for i in xrange(101)]
``````

2、求PI值。

``````	#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author: 黄哥python培训 qq:1465376564
"""
1 - 1/3 + 1/5 - 1/7 + ...

"""

def pi_series():
total = 0
i = 1.0
j = 1
while True:
total = total + j / i
yield 4 * total
i += 2
j = j * -1

def main(g, n):
for i in range(n):
yield g.next()

if __name__ == '__main__':
print list(main(pi_series(), 8))

#[4.0, 2.666666666666667, 3.466666666666667, 2.8952380952380956, 3.3396825396825403, 2.9760461760461765, 3.2837384837384844, 3.017071817071818]
``````

3、生成器处理大日志文本文本。

``````		# coding:utf-8

import time
start_time = time.time()

def find_ip(path):
for line in open(path):
s = line.find('"Sogou web spider')
if s >= 0:
yield line[:s].strip()

p = find_ip("bigfile.txt")
p = list(set(list(p)))
for item in p:
print item

print time.time() - start_time, "seconds"
``````

4、生成器函数也可以玩递归。

``````		#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author: 黄哥python培训 qq:1465376564

tmp = []
for item in lst:
if isinstance(item, list):
for item2 in tmp:
yield item2
else:
yield item

l = [1, 2, 3, 4, 5, [6], [7, 8, [9, [10]]]]
l2 = [[3, 7, [9, 6]], [2, [3, 4], 10], 99, 28]
l3 = []
l4 = [3, 4, 5, 8]
print list(lst)
print list(lst)
print list(lst)
print list(lst)

# [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# [3, 7, 9, 6, 2, 3, 4, 10, 99, 28]
# []
# [3, 4, 5, 8]
``````

×