Python Basics 13 - Iterators and Generators

iterators and generators

Anything that can use a for loop to get a value is an iterable 
iterable protocol:
those that contain __iter__ methods are iterable
iterator protocols
, and those that contain __iter and __next__ methods are iterators.
What is iteration? Iterator
iterator = iter (iterable). Comes with a __next__ method
Advantage: save memory\fast
feature: lazy operation
Commonly used: list\dictionary\element\string\set\range\file handle\enumerate
python 2 Different from the range in python3,
python2x kinds of ranges will generate a list regardless of the range, this list will be used to store all the values ​​in
python3, no matter the range, it will not actually generate heat
from
generator function:
any function with yield is a generator function;
the call of the generator function will not trigger the execution of the code, but will return a generator; if you want the generator function to execute, use next() to
record The current position, waiting
How to get the value from the generator?
1) next can be stopped at any time, the last time an error will be reported
2) for loop, traverse from beginning to end once, it will not stop if break\return is not encountered
3) An easy way to cast the return value of yield from the list\tuple data type
. If it is an iterable loop, and all elements in the iterable data are to be returned, you can use yield from
when using send. After the generator is created, it needs to be pre-activated, which can be implemented with a decorator. The
generator is used to solve the decoupling
list comprehension between memory problems and program functions:
[i for i in rang(30) if i%3==0 ]
Generator expression
(i for i in rang(30) if i%3==0)
A generator can only be taken once
, and the generator will not take a value when it does not find it to be worth it.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325321920&siteId=291194637