Iteration:
Iterator Protocol :
1. An iterator protocol means that an object must provide a next method that either returns the next item in the iteration, or causes a Stopiteration exception to terminate the iteration (only backward cannot go forward)
2. An iterative object: An object that implements an iterator protocol (how to: Define an __iter__ () method within an object)
3. The Protocol is a convention that iterates over objects, implements an iterator protocol, and Python's internal tools (such as for loops, sum,min,max functions, etc.) use an iterator protocol to access an object
the principle of iteration for A For loop :
1. Call the __iter__ () method to convert the subsequent sequence to an iterator object
2. Call the __next__ method, read the contents, and read the stopiteration exception to terminate the iteration.
name=[1,2,3,4,5] for in name: print(i) The principle of implementing a For loop: name= Name. __iter__ ()while True: try: print(name. __next__()) except stopiteration: break
Generator (Advantage: Save memory):
Generator: Can be understood as a type of data that automatically implements the iterator protocol (other data types need to call their own built-in __iter__ method), so the generator is an iterative object.
Generator classification and representation in Python: (Python provides generators in two different ways)
1. Generator function: general function definition, however, returns the result using the yield statement instead of the return statement. The yield statement returns one result at a time, in the middle of each result, suspends the state of the function so that the next time it leaves, it resumes execution.
2. Generator expression: similar to list derivation, however, the generator returns an object that produces results on demand, rather than building a list of results at a time
#function ExpressionA= (i forIinchRange (100))Print(a)Print(A.__next__())#function Expressiondefgenerator_test ():yield1yield2yield3b=generator_test ()Print(b)Print(b.__next__())Print(b.__next__())Print(b.__next__())Print(b.__next__())
View Code
Generator Summary:
1. is an iterative object
2. Delay calculation is realized, save memory Ah
3. The generator is essentially the same as the other data types, it is the implementation of the iterator protocol, but the generator attached a delay to calculate the benefits of saving memory, the rest of the iterative object can not be this benefit, remember!!!
How to trigger the function generator:
1.__next__
2.next ()
3.send () #send会将参数赋值给yield
Reference Link: https://www.cnblogs.com/linhaifeng/p/6133014.html
Python path-iterators and generators