First, generator
Cycle through the calculation of the mechanism, called the generator
Second, the characteristics of the generator:
1. Save Memory
2. When iterating to the next invocation, the parameters used are left for the first time, that is, the parameters of all function calls are preserved the first time they are called, not the newly created
Iii. Method of Creation
1. Change the list generation [] to ()
# List for in range (5)]print L# generator for in range (5 ))print G
The above code runs the result
[0, 2, 4, 6, 8]<generator object <genexpr> at 0x0000000002e40af8>
2. Yield Generation
Yield automatically terminates the return result.
The loop is down from where it was terminated.
def creatnum (): print ("----start----") = 0 While I < 5: yield i print(temp) I + = 1# Create a Generator object a = creatnum ()# Let the object begin execution, first execution from the beginning, if executed previously, Start from where you last stopped next (a)
The above code runs the result
----start---->>> next (a) None1>>> Next (a) none2>>> a.send (" Sqyy " ) sqyy3>>> Next (a) None
Iv. Additions:
Send ()
When performing to yield, the Gen function temporarily saves the value sent by send.
C.next () equivalent C.send (None)
"Code Learning" PYTHON Builder