First, the definition
Can be understood as a data type that automatically implements the iterator protocol (other data types need to call their own built-in __iter__ method), so the generator is an iterative object
Two types of generators (Python has two different ways to provide generators)
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 resumes execution.
yield Features:
1 Making the result of the function a raw iterator (encapsulating the __iter__,__next__ in an elegant way)
The 2 function pauses and resumes running state is by yield
deffunc ():Print(' First') yield11111111Print('Second') yield2222222Print('Third') yield33333333Print('Fourth') G=func ()Print(g) fromCollectionsImportIteratorPrint(Isinstance (G,iterator))#determines whether an iterator objectPrint(Next (g))Print('======>')Print(Next (g))Print('======>')Print(Next (g))Print('======>')Print(Next (g)) forIinchG:#I=iter (g) Print(i)
Note : Whatis the comparison between yield and return?
Same: function with return value
Different: Return only returns one value at a time, and yield can return multiple values
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
G= ('egg%s'%i forIinchRange (1000))Print(g)Print(Next (g))Print(Next (g))Print(Next (g)) with open ('a.txt', encoding='Utf-8') as F:#Res=max (Len (line) to line in F))Res=max (Len Line) forLineinchf)Print(RES)Print(Max ([1,2,3,4,5,6])) with open ('a.txt', encoding='Utf-8') as F:g= (Len (line) forLineinchf)Print(Max (g))Print(Max (g))Print(Max (g))
Third, the application
#[{' name ': ' Apple ', ' price ': 333, ' Count ': 3},] file contents#completion of the read and operate of the file through the generator expressionWith open ('Db.txt', encoding='Utf-8') as F:info=[{'name': Line.split () [0],' Price': Float (Line.split () [1]), 'Count': Int (Line.split () [2])} forLineinchFifFloat (Line.split () [1]) >= 30000] Print(info)
Python Builder and Apps