First, generator
1. Concept
In Python, a mechanism that loops one side of the computation, called the generator: generator
Create generator: G = (x*2 for x in range (5))
The next return value of the generator can be obtained through the next (generator) function
Throws a stopiteration exception when there are no more elements
The generator can also make a for loop because the generator is also an iterative object
2. The first way to build generator 1
for in Rang (+)]print(type (list2))# gets a generator object for in Rang (x)) Print(Type (g))# Print generator generates the first number
3. Generator
3.1 Using the loop to find the nth number of the Fibonacci sequence
def Feibo (items): = 1, 1, 3 while n <=items: ifor items ==2: return 1 else: =b, a +b print(b,end="" ) + = 1 return Bfeibo (4)
3.2 The second generation of generators yield
As long as there is a yield keyword in the function, this function becomes the generator
defFibo (N): a= 1b= 1I= 3ifn = = 1orn = = 2: return1 whileI <=N:a, b= B, A +b I+ = 1#The co-process allows the function to become the generator equivalent to a loop pause yieldbreturnb#get the Generator objectv = Fibo (10)#print it out in the form of a generatorPrint(Next (v))#traversing the generator with A for loop forXinchV:Print(x,end="\ t")
3.3 The usage of the generator send () must have a parameter
defTest (): I=0 whileI < 5:#assignment operation will be executed next yield will cause the program to stoptemp =yieldIPrint(temp) I+ = 1g=Test ()Print("-----Send----")Print(g.__next__())Print(Next (g))Print(G.send ("AAA") ) operation Result:-----Send---0None1AAA2
3.4 First call to send () exception problem
Solution:
1. First call using __next__ (), do not use Send ()
2. Or first use Send (None)
defTest (): I=0 whileI < 5: Temp=yieldIPrint(temp) I+ = 1g=Test ()Print("-----Send----")#an exception is caused by the first call without a parameter or by passing a non-none argumentPrint(G.send ())Print(G.send ("AAA"))
python--Core 2 (generator, iterator, closure, adorner) generator