首页 > 编程语言 > 详细

Python学习-迭代器和生成器

时间:2018-01-27 17:45:54      阅读:242      评论:0      收藏:0      [点我收藏+]
 1 ‘‘‘。在Python中,这种一边循环一边计算的机制,称为生成器:generator。
 2 要创建一个generator,有很多种方法。
 3 可以通过next()函数获得generator的下一个返回值‘‘‘
 4 
 5 def fib(max):
 6     n, a, b = 0, 0, 1
 7     while n < max:
 8         #print(b)
 9         yield b
10         a, b = b, a + b
11         n = n + 1
12     return done
13 
14 
15 #_*_coding:utf-8_*_
16 #@__author__ = ‘Alex Li‘
17 
18 import time
19 def consumer(name):
20     print("%s 准备吃包子啦!" %name)
21     while True:
22        baozi = yield
23 
24        print("包子[%s]来了,被[%s]吃了!" %(baozi,name))
25 
26 
27 def producer(name):
28     c = consumer(A)
29     c2 = consumer(B)
30     c.__next__()   #这样才能启用生成器
31     c2.__next__()  #这样才能启用生成器
32     print("老子开始准备做包子啦!")
33     for i in range(10):
34         time.sleep(1)
35         print("做了2个包子!")
36         c.send(i)
37         c2.send(i)
38 
39 producer("alex")
40 
41 #通过生成器实现协程并行运算
42 
43 #迭代器
44 """凡是可作用于for循环的对象都是Iterable(可迭代)类型;
45 凡是可作用于next()函数的对象都是Iterator(迭代器)类型,它们表示一个惰性计算的序列;
46 集合数据类型如list、dict、str等是Iterable但不是Iterator,不过可以通过iter()
47 if 函数获得一个Iterator对象:
48 """

 

Python学习-迭代器和生成器

原文:https://www.cnblogs.com/Ian-learning/p/8366561.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!