标签:
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