Generator Yield : Using the yield statement allows a function to generate a result sequence rather than just a value
def countdow (n): Print ("start!"); While N>0:yield N; N-= 1;c = Countdow (5);p rint (c.__next__ ()) print (c.__next__ ())
Output Result:
start!
5
4
__next__ () method causes the generator function to run until the next yield statement, at which point the __next__ () method passes the return value to yield and the function temporarily aborts execution to call __next__ () again when the function continues to perform this procedure until the generator function returns to the end
The __next__ () method is not usually called manually but uses a loop
For I in Countdow (5): print (i);
Output Result:
5
4
3
2
1
Generators are a powerful way to write programs based on processing pipelines, streams, or data streams;
Such as:
def tail (f): for-line-f:if not-line: #如果 non-true temporarily sleeps and tries again time.sleep (0.1); Continue Yield line; # generates a sequence of values from the obtained file values FileCount = tail (open (' e:/work.txt ')); #grep方法 used to find the specific substring in the method builder above def grep (Lines,searchtext): For the lines:if searchtext in Line:yield line;lines = grep (FileCount, ' Tom '); #查找带有tom substring for line in Lines:print (line);
Output Result:
' Tom ', 120,132
Summarize:
the role of the generator: when the program runs to yield, the running value is passed to the yield program and the output can be considered to be paused at this time when the program is in the suspended state when the __next__ () method is used, the function continues until the yield is encountered again
Advantage: Yield stores not a single value, but saves the current execution state of the program without having to compute all the elements at once, but using the same time to save memory space
This article is from the "Hong Dachun Technical column" blog, please be sure to keep this source http://hongdachun.blog.51cto.com/9586598/1769891
Generator yield in Python