Python3 生成器

Python中可以使用关键字yield将一个函数定义为一个生成器。生成器也是一个函数,可以生成一个值的序列,以便迭代使用。

生成器可以节约内存,提高内容使用效率。

生成器调用时,上次调用保存的变量不变。

e.g.1

def fun(n):
    print('fun exec a')
    for i in range(n):
        yield i
    print('fun exec b')
f_ge=fun(5)
for i in f_ge:
    print(i)

f_ge1=fun(6)

f_ge1.__next__()

 

输出:

fun exec a
0
1
2
3
4
fun exec b
fun exec a
0

e.g.2

def fun():

    print('hello' )

    m = yield 1

    print(m)

    d = yield 2

    print('World!')

f = fun()#返回生成器
ret1=next(f)#yield 返回值1,并给m
print(ret1)
ret2=f.send('Canshu')#ret2接收yield产生的2,send也会触发程序进入到下一个yield
print(ret2)
print(next(f))#没有下一个返回值,返回StopIteration异常并输出World

输出:

 

hello
1
Canshu
2
World!
---------------------------------------------------------------------------
StopIteration                             Traceback (most recent call last)
<ipython-input-7-26e7983a9cdd> in <module>
     16 ret2=f.send('Canshu')#ret2接收yield产生的2,send也会触发程序进入到下一个yield
     17 print(ret2)
---> 18 print(next(f))

StopIteration: 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章