python中yield
Python yield关键字 (Python yield keyword)
yield is a keyword (case-sensitive) in python, it is used to suspend the execution of a function and returns the value, if next time function calls, it resumes the function execution from the next statement where last execution was suspended.
yield是python中的一个关键字(区分大小写),用于暂停函数的执行并返回值,如果下次调用函数,它将从上次执行被暂停的下一条语句恢复函数执行。
Note: return keyword and yield keywords returns the value to the called function, but the return statement terminates the execution of the function, while yield statement just suspends the execution of the programs.
注意: return关键字和yield关键字将值返回给被调用的函数,但是return语句终止函数的执行,而yield语句只是挂起程序的执行。
Syntax of yield keyword
yield关键字的语法
def function_name():
statement(s):
yield value
statement(s)
Example:
例:
def sampleGenerate():
yield 100
yield 500
yield 800
收益关键字的Python示例 (Python examples of yield keyword)
Example 1: Demonstrate the example with yield keywords by returning values multiple times on function calls.
示例1:通过在函数调用中多次返回值,来演示带有yield关键字的示例。
# python code to demonstrate example of
# yield keyword
def sampleGenerate():
yield 100
yield 500
yield 800
# main code
for value in sampleGenerate():
print(value)
Output
输出量
100
500
800
Example 2: Find the squares of the numbers till a given maximum value of the square from main function.
示例2:从主函数中找到数字的平方,直到平方的给定最大值。
# python code to demonstrate example of
# yield keyword
def generateSquare():
count = 1
while True:
yield count*count
count += 1 # next function execution
# resumes from here
# main code
for i in generateSquare():
print(i)
if i>=100:
break
Output
输出量
1
4
9
16
25
36
49
64
81
100
翻译自: https://www.includehelp.com/python/yield-keyword-with-example.aspx
python中yield