Recently learned Python iterators and generators, the generator is a feature, is to use the data will be used to fetch! Look at the following code and think about it, and you'll understand what lazy computing is!
1 defAdd (S, x):2 returnS +x3 4 5 defGen ():6 forIinchRange (4):7 yieldI8 9 TenBase =Gen () One forNinch[1, 10]: ABase = (Add (i, N) forIinchbase) - Print(List (base))
Output: [20, 21, 22, 23] very puzzled, please look down
The key point of this problem is the following points:
1. Because the loop is doing is to generate data with the generator expression, and the generator has a lazy calculation characteristics, leading us to lead a road of no return, we are false illusion, in fact, it did not do anything, but simply walk on both sides of the process
2. The generator is waiting for the time to use (such as printing or next function to value, etc. ) will be calculated when the production, so wait until the last printing time to start the calculation
3. When the production data is started, the value of the two N of the loop has become 10.
4. The first cycle generator production number used to base or bound Gen take 0,1,2,3 processed (add function plus operation), the generator produced 10,11,12,13, and then base successfully occupy the generator
5. When the second loop is in the base value, base is no longer gen but the last loop rebinding base, so the value taken is 10,11,12,13 and then produced 20,21,22,23 by its own processing.
6. Do not think of the for-N in [1,10] as a for-N in range (1,10)
7. Maybe n becomes 10 very unexpected, but after understanding the inertia, it is understood that for the god of magic N is not in the 1 o'clock operation
8. It is important to clarify the binding relationship of base at a certain moment.
Hope this blog can help you! Thank you! Light Greetings!
Lazy Calculations for Python generators