Additional example of listening file end
deftail (): F= Open ('file','R', encoding='Utf-8') F.seek (0,2) whileTrue:line=F.readline ()ifLine :yield LineImportTime Time.sleep (0.1) G=tail () forIinchg:Print(I.strip ())
Send method
Send method:deffunc ():Print('*'*10) A=yield5Print(a)yield10g=func ()Print(g.__next__())Print(G.send ('Wenwen'))#print (g.__next__ ())
From which yield begins to execute, send passes a value to the yield
Send cannot be used in the first touch generator
The number of yield in the generator function must have how many next+send
def Averager (): = 0.0 = 0 = None while True: yield Averager + = term + = 1 = total/= Averager () Print(g_avg.__next__())print(G_avg.send (20))
Generator's pre-excitation adorner
Generator's pre-excitation adorner
Generator function: Generate a generator function
The essence of the generator is the iterator
Generator function Features: with yield keyword
And after the call, the code inside the function is not executed
How to trigger execution: Next send for loop
Next and send are data that are executed several times and may run out of data
The For loop is taken one at a time, and the For loop does not get an error until it is finished.
How to trigger execution:
Next
Send (optional): Send (None) = = _next_ (), send the base of next upload a value to the inside of the generator function
The send operation cannot be used for the first time in the generator
For loop
An example of fixing clothes in a clothing factory
defcloth (): forIinchRange (100): yield 'Clothes%s'%IG1=cloth () G2=cloth ()Print(G1.__next__())Print(G1.__next__()) forCinchcloth ():Print(c) forIinchRange (10): Print(G1.__next__()) forIinchRange (100):#because the total is 100, has taken 10, when the range is 100, the remaining 90 numbers are not enough to take 100 will be an error Print(G1.__next__()) forIinchf1[#This method will not be an error, how much to take Print(G1.__next__()) forCinchG1:Print(c)ifC.endswith (' the'): BreakPrint('*'*20) forCinchG1:Print(c)
Example: required execution result for ' A ', ' B ', ' C ', ' D '
deffunc (): a='AB'b='CD' #yield from a forIinchA:yieldI#yield from B forIinchB:yieldIG=func ()Print(g.__next__())Print(g.__next__())Print(g.__next__())Print(g.__next__())
G._next_ () can also be represented by next (g).
G._iter_ () can also be expressed in ITER (g).
Not all _ methods can use the method () to represent
python-Generator Advanced ~ Generator function