What is a generator?
Can be understood as a type of data that automatically implements an iterator protocol, so the generator is an iterative object. The generator can be said to provide a new pattern, which is to calculate a portion and then return the result of the calculation. However, the current state is preserved, and the next time it can be called in another place, it continues to execute in its previous state. This is very useful for programs that have a large amount of data. Overall is very strong ~ ~
There are two ways to produce a generator: a sound generator expression and a generator function.
One, generator expression:
# The generator expression and the list derivation are very similar, as long as the list derivation "" is changed to (). for in rangeprint(Next (G1)) #0Print (Next (G1)) # 1 Print (Next (G1)) # 4
Second, generator function
The generator function and the normal function are similar in format, with only a little difference. That is, the generator function does not need to return, but instead uses a new keyword yield. The yield statement has a main function of two points. One is to return the technical result of the current statement, and the second is to suspend the state of the function, and continue execution from the current position when the next call occurs.
About generator functions Let's look at a simple example first.
defG_func ():Print(' First') yield11111Print('Second') yield22222Print('Third') yield3333g=G_func ()Print(g)#<generator Object G_func at 0x0030e180>Print(Next (g))# First11111Print(Next (g))#Second22222Print(Next (g))#Third3333
Then let's look at an advanced point. Now we want to produce a number that is greater than a single prime. This is the result of an infinite number of sequences, so the normal method is not feasible. Even if there is a poor sequence, once our sequence length is large, the direct generation of this memory footprint is huge, but our generator can solve the problem perfectly. We can generate a generator and take as many as you want.
Import Mathdef is_prime (n): forIinchRange2,int(MATH.SQRT (n)) +1): ifN <=1: returnFalseifn%i==0: returnFalsereturntruedef creat_prime (n): whileTrue:ifis_prime (n):yieldprint (n) n+=1g=creat_prime (Ten) forIinchRange (100): Next (g)
Python Builder Summary