码迷,mamicode.com
首页 > 编程语言 > 详细

Python生成器的经典程序

时间:2015-04-07 22:59:07      阅读:179      评论:0      收藏:0      [点我收藏+]

标签:

import random
 
def get_data():
    """返回0到9之间的3个随机数"""
    return random.sample(range(10), 3)
 
def consume():
    """显示每次传入的整数列表的动态平均值"""
    running_sum = 0
    data_items_seen = 0
 
    while True:
        data = yield
        data_items_seen += len(data)
        running_sum += sum(data)
        print(The running average is {}.format(running_sum / float(data_items_seen)))
 
def produce(consumer):
    """产生序列集合,传递给消费函数(consumer)"""
    while True:
        data = get_data()
        print(Produced {}.format(data))
        consumer.send(data)
        yield
 
if __name__ == __main__:
    consumer = consume()#启动生成器
    consumer.send(None)
    producer = produce(consumer)
 
    for _ in range(10):
        print(Producing...)
        next(producer)

对比:yield作为语句还是表达式。

技术分享
import random
 
def get_data():
    """返回0到9之间的3个随机数"""
    return random.sample(range(10), 3)
 
def consume(data):
    """显示每次传入的整数列表的动态平均值"""
    running_sum = 0
    data_items_seen = 0
 
    while True:
        data = yield data
        """内部挂起生成器,yield作为表达式而不是语句"""
        """生成器运行时,yield返回一个值,就是外部通过send方法发送的值"""
        data_items_seen += len(data)
        running_sum += sum(data)
        print(The running average is {}.format(running_sum / float(data_items_seen)))
 
def produce(consumer):
    """产生序列集合,传递给消费函数(consumer)"""
    while True:
        data = get_data()
        print(Produced {}.format(data))
        consumer.send(data)
        yield
 
if __name__ == __main__:
    consumer = consume(0)
    consumer.send(None)
    producer = produce(consumer)
 
    for _ in range(10):
        print(Producing...)
        next(producer)
View Code

 

Python生成器的经典程序

标签:

原文地址:http://www.cnblogs.com/rgtv-wilkins/p/4399649.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!