生成器就是一个返回迭代器(iterator)的函数。 包含了 yield 的函数,就是一个生成器。

生成器每使用yield语句产生一个值,函数就会被冻结(暂停执行),被唤醒后(即再次调用)接着上次执行,继续产生新的值。

一个函数中可以包含多个yield,原理不变。

在一些情况下使用生成器可以节省存储空间。

 

示例一:

def gen():
    for i in range(5):
        yield i*2
for i in gen():
    print(i)

--------------------
0
2
4
6
8

 

示例二:

def gen():
    for i in range(3):
        print('step one')
        yield i
        print('step two')
        yield i*2
        print('step three')

for i in gen():
    print(i)

------------------------
step one
0
step two
0
step three
step one
1
step two
2
step three
step one
2
step two
4
step three

 

相关文章:

  • 2021-11-07
  • 2022-12-23
  • 2022-12-23
  • 2021-06-18
  • 2021-08-16
  • 2021-06-16
  • 2022-12-23
  • 2021-09-15
猜你喜欢
  • 2021-08-11
  • 2022-12-23
  • 2021-04-14
  • 2021-07-31
  • 2022-02-28
  • 2022-12-23
  • 2021-08-02
相关资源
相似解决方案