1. Introduction
With a list build, we can create a list directly, but with limited memory, the list size is bound to be finite.
If a list element can be inferred from an algorithm, can we continually extrapolate the subsequent elements in the process of looping?
In Python, this side loop computes the mechanism, called the generator: Generator.
2. Example
2.1 The list-generated [] change to (), a generator is created:
1 ( for in range (5)) 2 Print (s) # <generator Object <genexpr> at 0x02474a80> 3 # you can continue to get the return value through next (s), or use the For loop 4 for inch S: 5 Print (x)
2.2yield keywords
1 # non-wave pull series: 2 def fib (max): 3 N, a, b = 0, 0, 14while n < Max:5 print b6 C16/>a, B = B, A + b7 n = n + 1
Use the yield keyword:
1 #To turn the fib function into generator, just change print B to yield B.2 defFIB1 (max):3N, a, b = 0, 0, 14 whileN <Max:5 yield b6A, B = B, A +b7n = n + 18 9F = FIB1 (6)Ten PrintF#<generator Object fib1 at 0x026e4b20> One forXinchF: A PrintX
Description
1.generator and function execution flow is different.
2. The function is executed sequentially, the return statement is encountered, or the last line function statement is returned.
The 3.generator function executes at each call to next (), encounters a yield statement, and executes again from the yield statement that was last returned.
For example, the generator:
Line 10th calls the generator for the first time, runs to yield n stop (corresponding result is 16, 17 rows), 11 rows from yield n continues, because is the while loop body, after encountering yield n again stop (corresponding result is 18, 19 rows);
12 lines are similar to 11 rows.
1 defcreate_counter (n):2 Print "Create counter"3 whileTrue:4 yield n5 Print 'Increment n'6n + = 17 8CNT = Create_counter (1)9 PrintCNTTen PrintNext (CNT) One PrintNext (CNT) A PrintNext (CNT) - - #Output the #<generator Object Create_counter at 0x0000000001d141b0># Create Counter17 # 1# increment N19 # 2# increment N21 # 3
Python in builder