首页 > 编程语言 > 详细

python 生成器

时间:2018-02-04 13:35:16      阅读:181      评论:0      收藏:0      [点我收藏+]

python 生成器一共两种创建方法:

1,(x for x in range(5))

2,yield

# vim 3.py

def fib(max):
n,before,after = 0,0,1
while n < max:
yield before
before,after = after,before+after
n += 1

g = fib(8)
print (next(g))
print (next(g))
print (next(g))
print (next(g))
print (next(g))
print (next(g))
print (next(g))
print (next(g))

 

[root@localhost python]# python 3.py
0
1
1
2
3
5
8
13

 

# vim 4.py
def bar():
  print ("ok1")     #1

  count = yield 1
  print (count)

  yield 2


b = bar()
next(b)

ret = b.send("eeeeeeeeeeeeeeeee")
print (ret)

运行结果:

[root@localhost python]# python 4.py
ok1
eeeeeeeeeeeeeeeee
2
看现象。。。。。

 

python 生成器

原文:https://www.cnblogs.com/lixinliang/p/8412940.html

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