在Python中何时使用收益率而不是收益率?

yield语句暂停函数的执行,并将值发送回调用方,但保留足够的状态,使函数能够在停止的地方继续。恢复后,函数在最后一次运行后立即继续执行。这使得它的代码能够随着时间的推移生成一系列值,而不是一次计算它们并像列表一样将它们发送回去。

null

让我们看一个例子:

# A Simple Python program to demonstrate working
# of yield
# A generator function that yields 1 for the first time,
# 2 second time and 3 third time
def simpleGeneratorFun():
yield 1
yield 2
yield 3
# Driver code to check above generator function
for value in simpleGeneratorFun():
print (value)


输出:

1
2
3

回来 将指定的值发送回其调用者 产量 可以生成一系列值。当我们想要迭代一个序列,但不想将整个序列存储在内存中时,应该使用yield。

Python中使用了Yield 发电机 。生成器函数的定义与普通函数类似,但每当需要生成值时,它都会使用yield关键字,而不是return。如果def主体包含产量,该功能将自动变为发电机功能。

# A Python program to generate squares from 1
# to 100 using yield and therefore generator
# An infinite generator function that prints
# next square number. It starts with 1
def nextSquare():
i = 1
# An Infinite loop to generate squares
while True :
yield i * i
i + = 1 # Next execution resumes
# from this point
# Driver code to test above generator
# function
for num in nextSquare():
if num > 100 :
break
print (num)


输出:

1
4
9
16
25
36
49
64
81
100

本文由 阿比特·阿加瓦尔 .如果你喜欢GeekSforgek,并想贡献自己的力量,你也可以写一篇文章,然后将文章邮寄给评论-team@geeksforgeeks.org.看到你的文章出现在Geeksforgeks主页上,并帮助其他极客。

如果您发现任何不正确的地方,或者您想分享有关上述主题的更多信息,请写评论

© 版权声明
THE END
喜欢就支持一下吧
点赞11 分享