I. Iterative objects and iterators 1. The concept of iteration
The result of the last output is the initial value of the next input, and the repeating process is called an iteration, one iteration at a time, and the result of each iteration is the initial value of the next iteration
Note: Loops are not iterations
While True: #只满足重复, thus not iterative print (' ====> ')
2. An iterative object with built-in __iter__ methods is an iterative object.
List is an iterative object, Dict is an iterative object, and set is also an iterative object.
[1,2].__iter__() ' Hello '. __iter__() __iter__() {' A ': 1, ' B ': 2}.__iter__() {1,2,3}.__iter__ ()
For example:
x = [1, 2, 3]y = iter (x) z = iter (x) print (Next (y)) print (Next (y)) print (type ( x)) print (Type (y) )
Output
121<class ' list ' ><class ' List_iterator ' >
As shown
Here x
is an iterative object, y
and is a z
two independent iterator that holds a state inside the iterator that records where the current iteration is located, so that the correct element can be obtained at the next iteration.
Iterators have a specific type of iterator, for example list_iterator
, set_iterator
. An iterative object implements the __iter__
method that returns an Iterator object.
3. iterators
- 1. Why do I have iterators?
For data types that do not have an index, you must provide an iterative approach that does not depend on the index.
Iterator: An iterative object executes the __iter__ method, resulting in an iterator, an iterator object having a __next__ method
It is a stateful object that can return the next value in the next()
container when you invoke the method, any object that implements the __iter__
and __next__()
method is an iterator, __iter__
returns the iterator itself, __next__
returns the next value in the container, and if there are no more elements in the container, Throws the Stopiteration exception
- 3. Implementation of Iterators
Cases:
i=[1,2,3].__iter__() print (i) #迭代器print (i.__next__ ()) print (i.__next__()) Print (i.__next__ ()) #print (i.__next__ ()) #抛出异常: stopiteration
Output
<list_iterator Object at 0x1019c3eb8>123
next()
do two things each time the method is called:
- Modify state for Next call
next()
method
- Generates a return result for the current call
An iterator is like a lazy-loaded factory that returns a value when someone needs it, and waits for the next call when it is not called.
- 4. How to judge an iterator object and an iterator object
From collections import iterable,iterator ' abc '. __ITER__() (). __iter__() [].__iter__() {' A ': 1}.__iter __() {1,2}.__iter__() f=open (' A.txt ', ' W ') f.__iter__()
#判断是否为可迭代对象, the following are print (Isinstance (' abc ', iterable)) print (isinstance ([],iterable)) Print (isinstance ( ) (iterable)) print (Isinstance ({' A ': 1},iterable)) print (Isinstance ({},iterable)) print ( Isinstance (f,iterable))
#判断是否为迭代器, only the file is print (Isinstance (' abc ', Iterator)) print (isinstance ([],iterator)) Print (isinstance ( (), Iterator)) print (Isinstance ({' A ': 1},iterator)) print (Isinstance ({},iterator)) print (isinstance (F, Iterator))
Output
Truetruetruetruetruetruefalsefalsefalsefalsefalsetrue
Iterate objects: Only the __iter__ method, the iterator object that the method gets executed
Iterators: Have __iter__
and __next__()
methods
Note: For an iterator object, the __iter__ method is executed, and the result is still itself
- 5. Advantages and disadvantages of iterators
Advantages:
1. Provides an iterative approach that does not rely on subscript
2. More memory savings on the drop iterator itself
Disadvantages:
1. Unable to get the length of the iterator object
2. The value of the sequence type is flexible, is a one-time, can only be taken back to the value, not forward
Second, generator 1. Definition
The generator (generator) is a special iterator whose implementation is simpler and more elegant, and is the yield
key to the generator implementation __next__()
approach. It acts as a pause recovery point for the generator, you can assign a value to an yield
expression, or you can yield
return the value of an expression.
In other words, yield is a syntactic sugar, and the internal implementation supports the iterator protocol, while the yield is a state machine that maintains the status of suspend and continue.
Yield Features:
1. The equivalent of encapsulating __iter__ and __next__ for functions
2.return can only return one value at a time, the function terminates, and yield returns multiple values, each time it is returned, the function is paused, and next will continue from the last paused position.
Cases:
def counter (n): print (' Start ... ') i= 0 while i < N: yield i i+=1 Print (' End ... ') g=counter (5) print (g) print (Next (g)) print (Next (g)) print (Next (g)) print (Next (g)) print (Next (g)) # Print (Next (g)) #会报错
Output
Start ... 01234
2. Generator functions
- Generator functions: regular function definitions, however, use the yield statement instead of the return statement to return the result. The yield statement returns one result at a time, in the middle of each result, suspends the state of the function so that the next time it leaves, the execution continues;
Normal function return returns
def Lay_eggs (num): egg_list=[] for Egg in range (num): egg_list.append (' egg%s '%egg) return Egg_listyikuangdan=lay_eggs #我们拿到的是蛋print (yikuangdan)
Output
[' Egg 0 ', ' egg 1 ', ' Egg 2 ', ' Egg 3 ', ' Egg 4 ', ' Egg 5 ', ' Egg 6 ', ' Egg 7 ', ' Egg 8 ', ' Egg 9 ']
Iterator functions
def Lay_eggs (num): For -Egg in range (num): res= ' egg%s '% Egg yield res #生成器关键语法 Print (' Next egg ') Laomuji=lay_eggs #我们拿到的是一只母鸡print(Laomuji) print (laomuji.__next__ ()) #迭代 Egg 0print (laomuji.__next__ ()) #蛋1print (laomuji.__next__ ()) #蛋2egg_l =list (Laomuji) print (egg_l)
Output
Egg 0 under an egg 1 to finish an egg 2 under an egg under an egg next to finish an egg under an egg next end an egg next end an egg under an egg finish an egg [' Egg 3 ', ' Egg 4 ', ' Egg 5 ', ' Egg 6 ', ' Egg 7 ', ' Egg 8 ', ' Egg 9 ']
3. Generator expressions
- Builder 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;
Food=yield food_list
#g. Send (' Food1 '), first pass the food1 to yield, the yield is assigned to food, and then return to Food_list, and then proceed down until the yield is met again, then return the yield after the return value to Food_list
Cases
Note: The start generator cannot send a non-null value
Def eater (name): #协程函数 print ('%s eat '%name) food_list=[] While True: food= Yield food_list #装饰器表达式 food_list.append print ('%s start to eat%s '%(name,food)) g= Eater (' hexin ') print (g) #生成器
Print (G.send (' food1 ')) #传值
Output
Traceback (most recent): <generator object eater at 0x1049030f8> #生成器对象 File "/users/hexin/pycha rmprojects/py3/day5/2.py ", line <module> print (g.send (' food1 ')) Typeerror:can ' t send Non-none Value to a just-started generator #开始生成器不能send非空值
Def eater (name): #协程函数 print ('%s eat '%name) food_list=[] While True: Food=yield food_list #装饰器表达式 food_list.append print ('%s start to eat%s '%(name,food) ) g=eater (' hexin ') print (g) #生成器next (g) #等同于 G.send (None), Initialize print (G.send (' food1 '))
Output
<generator object eater at 0x107cde258> hexin "ready to eathexin" start to eat food1[' food1 ']
- To prevent forgetting to initialize, the adorner can be initialized with the following
def deco (func): #初始化函数 def wrapper (*args,**Kwargs): res=func (*args,**Kwargs) Next (RES) #等同于 g.send (None), initialize return res return Wrapper@deco #用初始化函数装饰器, call the initialization function Def eater (name) : #协程函数 print ('%s ready to eat '%name) food_list=[] While True:food=yield food_list # Adorner expression food_list.append (food ) print ('%s start to eat%s '%(name,food)) g=eater (' Hexin ') # print (g) #生成器 # Next (g) #等同于 G.send (None), Initialize print (G.send (' food1 ')) print (G.send (' food2 '))print (g.send (' food3 '))
Output
Hexin-eathexin start to eat food1[' food1 ']hexin start-to-eat food2[' food1 ', ' food2 ']hexin start to eat food3[' food1 ', ' food2 ', ' food3 ']
"Python iterator, generator"