can iterate over objects
strings, lists, Ganso, collections, dictionaries are iterative, and numbers are non-iterative . (You can iterate through the inner element with a for loop)
How to see if a variable is an iteration:
from collections Import iterable l = [1,2,3,4" t = (1,2,3,4) d = {1:2,3:4} s = {1,2,3,4} print (Isinstance (l,iterable)) Span style= "COLOR: #0000ff" >print (Isinstance (t,iterable)) print (Isinstance (d,iterable)) print (Isinstance (s,iterable)) #
A requirement that can be iterated over is called an iterative protocol. the definition of an iterative protocol is that the __ITER__ method is implemented internally, and the __iter__ method can be encapsulated in an iterative object .
iterators
iterators : You can generate an iterator after the variable is __iter__, and the iterator follows the iterator protocol: You must have the __iter__ method and the __next__ method.
L = [1,2,3,4]l_iter= L.__iter__()#L_iter is just an accepted variable.item = L_iter.__next__()#using iterators to take valuesPrint(item)#1item = L_iter.__next__()Print(item)#2item = L_iter.__next__()Print(item)#3item = L_iter.__next__()Print(item)#4item = L_iter.__next__()Print(item)#exceeding limit, error
The last step in the final error situation, in order to make the program does not give an error, you can end it after the end of the finished:
L = [1,2,3,4= L.__iter__() while True: try: = L_iter. __next__ () print(item) except stopiteration: Break
Generator
Generator:(essentially an iterator, just written by the programmer called the generator, built-in called iterators)
1. Generator function: General function definition, however, returns the result using the yield statement instead of the return statement. 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, it continues to execute, inert.
2. Generator 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
Simple generator:
Import Timedeffunc (): a= 1Print('The A variable is now defined') yielda B= 2Print('and now we've defined the B variable.') yieldbg1=func ()Print('G1:', G1)#print G1 can be found G1 is a generatorPrint('-'*20)#I'm a gorgeous split line.Print(Next (G1)) Time.sleep (1)#sleep a second to see the execution processPrint(Next (G1))#Each print will come out with a yield value, or it will hang on the previous yield without continuing execution .
What are the benefits of generators? is not to generate too much data in memory at once, only when you want to give you the data you want
Several small chestnuts applied by the generator:
For clothing Orders:
defProduce ():"""Production of clothing""" forIinchRange (2000000): yield "produced the first piece of%s clothes"%Iproduct_g=Produce ()Print(Product_g.__next__())#want a piece of clothingPrint(Product_g.__next__())#I need another dress .Print(Product_g.__next__())#I need another dress .num =0 forIinchProduct_g:#want a batch of clothes, like 5 pieces Print(i) Num+=1ifnum = = 5: Break#here we have 8 pieces of clothes for the factory, and I have made my production function (that is, the produce generator function) to produce 2 million pieces of clothing. #There's a lot of clothes left, we can keep them, we can keep them when we want to take them.
View Code
The generator listens for file input chestnuts:
Import Timedeftail (filename): F=open (filename) f.seek (0,2)#count from the end of the file whileTrue:line= F.readline ()#read new lines of text in a file if notLine:time.sleep (0.1) Continue yieldLinetail_g= Tail ('tmp') forLineinchTail_g:Print(line)
View Code
Calculate the moving average (similar to the annual yield):
def Averager (): Total = 0 day = 0 average = 0 while true:term = yield average total += term day + = 1 Average = Total/dayg_avg = Averager () next ( G_AVG) print (g_avg.send (10 Span style= "COLOR: #0000ff" >print (g_avg.send (12 print (g_avg.send)
View Code
yield from can reduce the code while implementing the For loop effect:
defgen1 (): forCinch 'AB': yieldC forIinchRange (3): yieldIPrint(List (Gen1 ()))#[' A ', ' B ',------]#Simplified versiondefGen2 ():yield from 'AB' yield fromRange (3)Print(List (Gen2 ()))#[' A ', ' B ',------]
list derivation and generator expressions:(Here is a small story to explain the knowledge points)
#in order to show the essence of high-rich handsome, bought 10 tea egg, and they line up and numbered, photos sent to the circle of friendsegg_list=['Tea Egg%s'%i forIinchRange (10)]#List Parsing#but these 10 tea egg can not finish the breath, to eat is also a eat, then eat a picture of itEat=('Tea Egg%s'%i forIinchRange (10))#Builder ExpressionPrint(EAT)Print(Next (Eat))#Next is essentially calling __next__ .Print(Eat.__next__())Print(Next (Eat))
ko fu Shuai and tea egg
Summarize:
1. The [] Conversion of the list parsing [] to () is the generator expression
2. List parsing and builder expressions are a convenient way of programming, except that generator expressions are more memory-efficient
3.Python uses the iterator protocol to make the For loop more general. Most built-in functions also access objects using an iterator protocol.
attached: The interview questions related to the builder:
def demo (): for in range (4): yield ig=demo () G1- in g) G2 for in G1)print(list (G1))#[0,1,2,3] Print(list (G2))#[]
face question 1
def add (n,i ): return n+i def Test (): for i in range (4 yield IG =test () for n in [1,10 ]: G = (Add (n,i) for i in g) print (List (g)) # [20,21,22,23]
Face question 2
What's the Python iterator object, iterator, and generator (with interview questions)