generator 生成器

L=[i*i for i in range(10)]
    print(L)
G=(i*i for i in range(10))  #变中括号为小括号
    print(G)

另一种方法:

fib(max):
    n,a,b=0,1,1
    while n<max:
        #print(b)
        yield b    
        a,b=b,a+b
        n+=1
        return 'done'

但是用for循环调用generator时,发现拿不到generator的return语句的返回值。如果想要拿到返回值,必须捕获StopIteration错误,返回值包含在StopIterationvalue中:

 g = fib(6)
 while True:
     try:
        x = next(g)
        print('g:', x)
     except StopIteration as e:
         print('Generator return value:', e.value)
         break

g: 1
g: 1
g: 2
g: 3
g: 5
g: 8
Generator return value: done

 

posted @ 2018-05-11 15:39  ming_z  阅读(196)  评论(0编辑  收藏  举报