Generator *************
In Python, this side loop calculates the mechanism, called the Generator (Generator), which saves a lot of space.
List generation, which consumes memory when the element is printed when it is generated.
One, two ways to read the generator elements:
*L.next ()
* forLoop read ; (generator is an iterative object);
List generation, when the element is printed when generated, it consumes memory;
In [5]: L = [i-I in range (1,11)]
In [6]: Print L
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
In [7]: H = (I-I in range (1,11)) #将 [] to () to create a generator
*) generator is an iterative object
In [All]: from collections import Iterable #导入模块
In [all]: LH = (i**2 for I in range (3))
In []: Isinstance (lh,iterable) #判断
OUT[13]: True
*for Loop Read
Practice : Generates the famous Fibonacci sequence (Fibonacci), except for the first and second numbers, any number
Can be added from the first two numbers
1, 1, 2, 3, 5, 8, 13, 21, 34, ...
Second, *) yield keyword
A. If there is a yield keyword inside a function, the variable assigned to the result of calling this function is the generator
B. When the generator G invokes the first next method, the function is run until the first yield stop is encountered
C. When the second next method is called, execution continues from where it was stopped, knowing that the next yield is encountered
*) The relationship of the next method to the yield keyword
in [+]: Print Lh.next () # first Next, encounters the first Yirld end, prints 1
First
1
in [+]: Print Lh.next () #第二个next, encounters the end of the second Yirld, prints 2
Second
2
In [Lh.next]: Print () #第三个next, encounters a third Yirld end, printing 3
Third
3
Three, *) Generator's Send method
A. Using the Send method to send data to the generator function
B. Before using the Send method, you must first call the next () method
C. Encountering the next yield stop
*) consumer-producer model
*) Builder app: Mini chat Robot
python-Advanced Features