Generator
The function with yield is called generator (generator) in Python
defXragns ():#Defining function Generators Print('little Guy') yield('Good')#plus yield generates a generator Print('python') yield('Hao') Print('Programming') yield('Hao') x= Xragns ()#executing a function generator is just getting inside not executingret = x.__next__()#the next method of the generator will only execute the execution function to find the next yieldPrint(ret) RET= x.__next__()#the second execution goes back to where it was last time.Print(ret) RET= x.__next__()Print(ret)
Iterators
Iterators are a way to access the elements of a collection. An iterator object is accessed from the first element of the collection, knowing that all of the elements have been accessed and finished. Iterators can only go forward and not back
EF xrange (N):#Define a functionStart =0 whileTrue:#While Loop ifStart > N:#Judging if the value is less than n return yieldStart#Generator ExitsStart + = 1#each cycle to this adds a forIinchXrange (10):#iterators Print(i) obj= Xrange (5)#executes the function, and the generator does not execute internally at this timeN1 = obj.__next__()#The generator executes from top to bottom knowing the first yield encounteredN2 = obj.__next__()#the generator goes back to where it was last jumped and goes back to the loop.N3 = obj.__next__()#Next, you want to executeN4 = obj.__next__() N5= obj.__next__() N6= obj.__next__() N7= obj.__next__()Print(N1,N2,N3,N4,N5,N6)#output all the results#
Python First Knowledge builder iterator