Iterators and generators
any value that can be used for a loop is an iterative
Iterative protocol:
Internally containing the __iter__ method is an iterative
iterator protocol
that contains both the __iter method and the __next__ method are iterators
What is iterator
iterator =iter (iterative). Bring a __next__ method
Advantage: Save memory \ Fast
Properties: Lazy Operation
Common: list \ dictionary \ element \ string \ collection \range\ file handle \enumerat e
Range Differences in Python 2 and Python3
python2x range No matter what range, a list is generated that will be used to store all values
Python3, regardless of range, Doesn't actually generate heat. A value of
Python3, with the yield from
Generator function:
Any function with yield is a generator function;
The call to the generator function does not trigger the execution of the code, but instead returns a generator, wants the generator function to execute, uses next ()
to record the current location, and waits for
How to take the value from the generator?
1) Next can be stopped at any time, the last time it will error
2) for loop, traversal from beginning to end, do not encounter Break\return does not stop
3) list\tuple data type cast
The simple method of yield return value, if itself is the loop of an iterative, and to the iteration of the data is not an element in return, you can use the yield from the
when using send, after the generator created by the need for pre-activation, can be implemented with adorners.
A generator is used to solve the decoupling of memory problems and program functions
List derivation:
[I for I in rang () if i%3==0]
Generator expression
(I for I in rang () if i%3==0)
A generator can only be taken once
the generator does not find him to be worth the time, not the value.
Python basic 13-iterators and generators