I. What is an iterator protocol
1, the iterator protocol means that the 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, not 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, an iterative object implements an iterator protocol, an internal tool in Python (for example: For loop, Sum,min,max function, etc.) uses an iterator
Protocol Access Object
Two. Powerful for loop mechanism in Python
The nature of the For loop: Loop through all objects, all using an iterator protocol
(strings, lists, tuples, dictionaries, collections, file objects) These are not iterative objects, except for in the loop, they call their __iter__ method,
Turn them into an iterative object, and the For loop invokes the __next__ method of the iteration object to fetch the value, and the for loop catches the stopiteration exception to
Terminate Iteration
1List_test = [11,22,33]2List_iter = List_test.__iter__()3 Print(List_iter.__next__())# One4 Print(List_iter.__next__())# A5 Print(List_iter.__next__())# -6 Print(List_iter.__next__())#out of Bounds, error stopiteration7 8 #the For Loop List_test essentially follows the way the iterator is accessed,9Call List_iter = List_test first.__iter__() method, or direct List_iter =iter (list_test)Ten then execute List_iter.next () in turn until the for loop snaps to the stopiteration termination loop One A #For Loop The essence of all objects is the same truth - - #Now let's use the while to simulate what the for loop does. theList_test = [11,22,33] -List_iter = List_test.__iter__() - whileTrue: - Try: + Print(List_iter.__next__()) - exceptstopiteration: + Print("The iteration is complete and the loop is terminated.") A Break
In the above way, we can see that the for loop is based on an iterator protocol that provides a uniform way to traverse all objects, that is, before the traversal
First call the object's __iter__ method to convert it to an iterator, and then use an iterator to iterate through it so that all objects can be passed through a for loop
Traversed the
Third, generator
The generator can be understood as a data type 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
The builder behaves in Python:
1, Generator function: The general function definition, however, returns the result using the yield statement instead of the return language, and the yield statement returns one result at a time, in the middle of each result,
Suspends the state of the function's current period so that the next time it (yield) leaves the place to continue 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
Advantages of the generator:
Python uses generators to provide support for deferred operations, which are called deferred operations that produce results when needed, rather than producing results immediately
Generator Summary:
1, which is an iterative object
2, it realizes the delay calculation, saves the memory
3, the generator book and other data types are implemented iterator protocol, but the generator attached a delay to calculate the taste of memory,
The rest of the iterative objects do not have this function
Four: Generator functions
1 defLay_eggs (num):2Egg_list = []3 forEgginchrange (num):4Egg_list.append ('Egg%s'%egg)5 returnegg_list6 7Total = Lay_eggs (10)8 Print(total)9 Ten #[' Egg 0 ', ' egg 1 ', ' Egg 2 ', ' Egg 3 ', ' Egg 4 ', ' Egg 5 ', ' Egg 6 ', ' Egg 7 ', ' Egg 8 ', ' Egg 9 '] One A - defLay_eggs (num): - forEgginchRangenum): theresult ='Egg%s'%Egg - yieldresult - Print('it's an egg.') - +Total = Lay_eggs (10)#we got an old hen that can lay eggs according to our needs. - Print(total) + Print(Total.__next__()) A Print(Total.__next__()) at Print(Total.__next__()) -egg_l =list (total) - Print(egg_l) - #The demo can only go backwards.
V: Generator Expressions and List parsing
1 #Three -dimensional expression2 #true Result---expression---false result3 4Name ='Ying'5res ='very good' ifName = ='Ying' Else 'does not exist'6 Print(RES)#very good
List resolution Cases
1 #List Parsing2 3Egg_list = ['Egg%s'%i forIinchRange (10)]4 Print(egg_list)5 #[' Egg 0 ', ' egg 1 ', ' Egg 2 ', ' Egg 3 ', ' Egg 4 ', ' Egg 5 ', ' Egg 6 ', ' Egg 7 ', ' Egg 8 ', ' Egg 9 ']6 7 8 #Builder Expression9Egg_list = ('Egg%s'%i forIinchRange (10))Ten Print(egg_list) One Print(Next (Egg_list))#Next is essentially calling __next__ . A Print(Egg_list.__next__()) - - the #<generator Object <genexpr> at 0x000000000113c1a8> - #Egg 0 - #Egg 1
Summary:
1, the list parsing [] replaced () is the generator expression
2, list parsing and builder expressions are all programmatic, except that generator expressions are more memory-efficient
3,python not only uses the iterator protocol to make the For loop more generic, most built-in functions, but also those that use the iterator protocol to access the object
For example, the SUM function is a built-in function of Python that accesses an object using an iterator protocol, and the generator implements the iterator protocol, so
We can do this directly to calculate a series of values and
1 Print for in range) # All numbers added and 2print for in # I of 2 times, 285
Instead of superfluous, build a list and calculate:
1 for inch Range (10)])
Iterators and generators (i)