python yield

带有yield的函数的返回值g就是generator,generator保存的是算法,每次调用next(g),就计算出g的下一个元素的值,直到计算到最后一个元素,没有更多的元素时,抛出StopIteration的错误。

当然,上面这种不断调用next(g)实在是太变态了,正确的方法是使用for循环,因为generator也是可迭代对象:

 

 

例子

def count_up_to(max):
     count = 1
     while count <= max:
        yield count
        count += 1

for count in count_up_to(3):
   print(count)

输出

1
2
3

 

posted @ 2025-09-02 17:39  金一九  阅读(6)  评论(0)    收藏  举报