yield 是 Python 中用于定义**生成器(generator)**的关键字。与 return 不同,yield 在函数中每次调用时会"产出"一个值,并暂停函数的执行状态;下次再调用时,从上次暂停的位置继续执行。
一、基本用法
示例 1:简单生成器
def simple_generator():
yield 1
yield 2
yield 3
gen = simple_generator()
print(next(gen)) # 输出: 1
print(next(gen)) # 输出: 2
print(next(gen)) # 输出: 3
# print(next(gen)) # 抛出 StopIteration 异常
也可以用 for 循环遍历:
for value in simple_generator():
print(value)
# 输出:
# 1
# 2
# 3
二、yield vs return
return:函数执行完就结束,返回一个值。yield:函数变成生成器,可以多次返回值,每次调用恢复执行。
三、带参数的生成器(生成器表达式)
def countdown(n):
while n > 0:
yield n
n -= 1
for i in countdown(5):
print(i)
# 输出: 5 4 3 2 1
这种写法非常节省内存,因为不会一次性生成所有值。