What is an iterator
An iterator is an iterative tool
An iteration is a repeating process, one iteration at a time, and the result of each iteration is the initial value of the next iteration
while True: # Here is a simple repetition, not an iterative print('-----')
L = [<== 0 while Count Len (l): # Here is the iteration Print(L[count]) + = 1
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
2. Iterative objects: Objects that implement an iterator protocol (an __iter__ () method is defined within an object)
3, the Protocol is a convention, can iterate over the object to implement the iterator protocol, Python's internal tools (such as for loop, Sum, Min, max function, etc.) using the iterator protocol to access the object
For sequence types, such as strings, list tuples, and so on, we can iterate through its contained elements using an index, but for unordered types: dictionaries, collections, files, etc. are not indexed, so if we want to take out the elements that are contained inside, we must find a way to not depend on the index
An iterative object refers to an object that has a built-in method __iter__:
'Hello'.__iter__().__iter__[(a).__iter__{'a': 1}.__iter__{'a','b'}.__iter__{'a','b'}.__iter__Open ('a.txt').__iter__
The result of an iterative object execution Obj.__iter () is an iterator object
An iterator object is an object that has a built-in __iter__ and a built-in __next__ method.
File type is an iterator object
Open ('a.txt'). __iter__ Open ('a.txt'). __next__
An iterator object must be an iterative object, and an iterative object is not necessarily an iterator object
DIC = {'a': 1,'b': 2,'C': 3} iter_dic= dic.__iter__()#The iterator object is obtained, and the iterator object is __iter__ and __next__, but the iterator. __iter__ () still gets the iterator itselfIter_dic.__iter__() isIter_dic#TruePrint(Iter_dic.__next__())#Next (iter_dic)Print(Iter_dic.__next__())#Next (iter_dic)Print(Iter_dic.__next__())#Next (iter_dic)#print (iter_dic.__next__ ()) #抛出异常StopIteration, EndIter_dic= dic.__iter__() while1: Try: K=Next (iter_dic)Print(Dicp[k])exceptstopiteration: Break
For loop
DIC = {'a': 1,'b': 2,'C': 3} forKinchDIC:Print(Dic[k])#how the For loop works#1. Execute the dic.__iter__ () method of the in object to get an iterator object Iter_dic#2. Perform next (iter_dic), assign the resulting value to K, and then execute the Loop code body#3. Repeat the process 2 until you catch the abnormal stopiteration and end the loop
Advantages and disadvantages of iterators
Advantages:
A unified, index-independent iterative approach
Lazy calculation, save memory
Disadvantages:
Unable to get length (only after next finishes knowing that there are several values)
One-time, can only go back, can not forward
Generator
As long as there is a yield keyword inside the function, the result of the function name () is the generator, and the function internal code is not executed
def Test (): yield 1 yield 2 yield 3print(test)# The result is: <function test At 0x01e79d68>Test (). __next__ ()
Yield
Make a function an iterator
Compare Retrun, you can return multiple values, you can suspend/save the function's running state
Generators are iterators
A.__iter__A. __next__ = Next (a)print(res)
Builder expression
List parsing
A = ['jidan%s' for in range (10)]
The generator expression is the result of the [] change to () of the list parsing.
A1 = ('jidan%s' for in range (10))
List parsing and builder expressions are a convenient way of programming, except that generator expressions are more memory-efficient
Python uses an iterator protocol to make a for loop more general, and most built-in functions, which also use an iterator protocol to access objects, such as the SUM function is a python built-in function that accesses an object using an iterator protocol, and the generator implements the iterator protocol. So we can calculate the value of a series of values directly:
for in range)print(s)# The result is: 285
Instead of having to build a list first:
for in range (10)])
iterators, generators in Python