码迷,mamicode.com
首页 > 其他好文 > 详细

生成器

时间:2016-08-04 01:36:24      阅读:199      评论:0      收藏:0      [点我收藏+]

标签:

技术分享

g = (x * x for x in range(10))
print(next(g)) #0
print(next(g)) #1
print(next(g)) #4
print(next(g)) #9
print(next(g)) #16

for n in g:
    print(n) # 25 36 49 64 81
def fib(max):
    n, a, b = 0, 0, 1 # n=0 a=0 b=1
    while n < max:
        #print(b)
        yield b
        a, b = b, a + b #a=b b=a+b
        n = n + 1
    #return ‘done‘ 不能有return

f = fib(6)
print(next(f)) #1
print(next(f)) #1
print(next(f)) #2
print(----) 
for n in f: #3 5 8
    print(n)
def odd():
    print(step 1)
    yield 1
    print(step 2)
    yield 2
    print(step 3)
    yield(3)

o = odd()
print(next(o)) #1
print(next(o)) #2
print(next(o)) #3
print(next(o)) #StopIteration
#while True:
#    try:
#        x = next(o)
#        print(‘g‘, x)
#    except StopIteration as e:
#        print(‘Generator return value‘, e.value)
#        break

 

生成器

标签:

原文地址:http://www.cnblogs.com/jzm17173/p/5735105.html

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