生成器是一种函数,它允许指定一个函数,该函数的作用类似于迭代器,因此可以在for
循环中使用。在生成器函数中,yield
关键字替代了 return
语句。
# Simple Python function
def fn():
return "Simple Python function."\n
# Python Generator function
def generate():
yield "Python Generator function."\n
print(next(generate()))
运行得到结果:
Python Generator function.