小马过_河

导航

知识点

生成器 
  
>>> g = (x * x for x in range(10))
>>> g
<generator object <genexpr> at 0x1022ef630>

def fib(max):
    n, a, b = 0, 0, 1
    while n < max:
        yield b
        a, b = b, a + b
        n = 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 on 2018-03-11 21:04  小马过_河  阅读(131)  评论(0编辑  收藏  举报