Iterators
Index: 1 = [+]
For loop: For I in L:
I
Print (dir ([])) tells the list all the methods
As long as the data type that can be used for loop must have the __iter__ method
Print ([].__iter__ ())
A list that executes the return value after __iter__ () is an iterator
Print (dir ([])) Print (dir ([]. __iter__()))print(Set (dir ([]). __iter__()))-Set (dir ([])))
Iterable Iterative--> __iter__ #只要含有__iter__方法的都是可迭代的
[].__iter__ () iterator--> __next__ #通过next就可以从迭代器中一个一个的取值
As long as the __iter__ method is iterative-iterative protocol
The concept of iterators
Iterator protocol--an iterator that internally contains __next__ and __iter__ methods
Iterator protocols and iterative protocols:
Can be iterated by the For loop
There are __iter__ methods in an iterative interior
As long as the iterator is bound to iterate
An iterator can be obtained by iterating over the. __iter__ () method.
The __next__ () method in the iterator can get the value one by one
The For loop is actually using iterators
Iterator
Can iterate over objects
Just give you the memory address.
Print ([]. __iter__ ())print(range (10))
For
It is only possible to iterate over objects to use the for
When we come across a new variable, unsure if it can be used for a loop, we'll tell if it's iterative.
for inch L: Pass = L.__iter__() iterator. __next__ ()
Benefits of Iterators:
A value from one of the container types will fetch all the values.
Saves memory space
Iterators do not occupy a large chunk of memory in memory,
Instead, each time the loop generates a
Every time next time you give me a
Generator
Generator-Iterator
def generator (): Print (1) return ' a ' = Generator ()print(ret)
Generator functions--essentially, we write our own functions.
Builder expression
L = [1,2,3,4,5] for in L: print(i) if i = = 2 : Break for inch L: Print (i)
As long as the function containing the yield keyword is a generator function
Yield cannot be shared with return and needs to be written inside the function
def generator (): Print (1) yield ' a '
#生成器函数: After execution, you get a generator as the return value
ret = Generator ()print(ret)print(ret.__next__())
Python functions (iterators, generators)