Creating generators
1 #the first way to create a generator2 #use () to create a generator, and create a list if you use []3A = (x**2 forXinchRange (1, 5))4 #you can always generate new data through next until the last report exception, through the for traversal will not report the exception5 #You can also use a.__next__ ()6 Print(Next (a))#Output 17 Print(A.__next__())#Output 48 Print(Next (a))#Output 99 Ten #traversing the generator with for One forIinchA: A Print(i) - - #the second way to create generators the defcreatenum (n): - forIinchrange (n): - yieldI**3 - + forIinchCreatenum (5): - Print(i)
The generator's send usage generator.send (value)
1 #the generator's send usage generator.send (value)2 defTest ():3i = 14 whileI < 5:5temp =yieldI**26 Print(temp)7i + = 18 9t =Test ()Ten #The first run can only use Next or send (None) One Print(T.__next__()) A #the function of send is equivalent to keeping the generator running, and the passed parameter is the return value of yield (the value of temp in the program) - Print(T.send ("Hello World")) - Print(T.__next__())#equivalent to send (none) at this time temp = none
Python generator yield and send