Generator yield: Using yield statements
You can let a function generate a result sequence, not just a value
def Countdow (n): print ("start!"); While n>0: yield n; n-= 1; c = Countdow (5); Print (c.__next__ ()) print (c.__next__ ())
Output Result:
start!54
The __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
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
Instead, use loops
For I in Countdow (5): print (i);
Output Result:
54321
Generators are a powerful way to write programs based on processing pipelines, streams, or data streams;
Such as:
def tail (f): For line in F: If is not line: #如果 non-true temporarily hibernate and try Time.sleep again (0.1); Continue; Yield line; # generates a sequence of values from the obtained file values filecount = tail (open (' e:/work.txt ')); #grep方法 used to look up a specific substring in the method builder above def grep (lines,searchtext): For line in lines: if searchtext on 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: The value that will run when the program runs to yield
Passed to the yield program does not output can be considered at this time the program is in a paused state when using the __next__ () method The function continues execution
Until the yield is met 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
The above is the content of the generator yield in Python, more relevant content please pay attention to topic.alibabacloud.com (www.php.cn)!