31

Python中的Yield用法

 3 years ago
source link: http://www.banbeichadexiaojiubei.com/index.php/2020/10/17/python中的yield用法/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

带有yield的函数在Python中被称之为generator(生成器),也就是说, 当你调用这个函数的时候,函数内部的代码并不立即执行 ,这个函数只是返回一个生成器(Generator Iterator)。

def generator():
    for i in range(10) :
        yield i*i

gen = generator()
print(gen)

<generator object generator at 0x7ffaad115aa0>

1. 使用next方法迭代生成器

generator函数怎么调用呢?答案是next函数。

print("first iteration:")
print(next(gen))

print("second iteration:")
print(next(gen))

print("third iteration:")
print(next(gen))

print("fourth iteration:")
print(next(gen))

程序输出:

first iteration:
 0
 second iteration:
 1
 three iteration:
 4
 four iteration:
 9

在函数第一次调用next(gen)函数时,generator函数从开始执行到yield,并返回yield之后的值。

在函数第二次调用next(gen)函数时,generator函数从上一次yield结束的地方继续运行,直至下一次执行到yield的地方,并返回yield之后的值。依次类推。

2. 使用send()方法与生成器函数通信

def generator():
    x = 1
    while True:
        y = (yield x)
        x += y

gen = generator()
		
print("first iteration:")
print(next(gen))

print("send iteration:")
print(gen.send(10))

代码输出:

first iteration:
 1
 send iteration:
 11

生成器(generator)函数用yield表达式将处理好的x发送给生成器(Generator)的调用者;然后生成器(generator)的调用者可以通过send函数,将外部信息替换生成器内部yield表达式的返回值,并赋值给y,并参与后续的迭代流程。

3. Yield的好处

Python之所以要提供这样的解决方案,主要是内存占用和性能的考量。看类似下面的代码:

for i in range(10000):
    ...

上述代码的问题在于,range(10000)生成的可迭代的对象都在内存中,如果数据量很大比较耗费内存。

而使用yield定义的生成器(Generator)可以很好的解决这一问题。

参考材料

https://pyzh.readthedocs.io/en/latest/the-python-yield-keyword-explained.html

https://liam.page/2017/06/30/understanding-yield-in-python/


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK