I. Application of the co-process function
Write an adorner that allows the function to perform the next () function without input
Analysis: Generates a generator of this function in the adorner and executes the next () function once
defFirstnext (func):defWrapper (*args, * *Kwargs): G= Func (*args, * *Kwargs) Next (g)returngreturnwrapper @firstNextdefEater (name):Print("{} start to eat". Format (name)) Food_list= [] whileTrue:food=yieldfood_listPrint("{} eat {}". Format (name, food)) Food_list.append ( food) G= Eater ("Egon")Print(G.send ("steamed Bun"))Print(G.send ("Noodles"))
Two. Process-oriented programming
Implement the Grep-rl ' Python ' c:/test functionality
a function implementation
ImportOSdefSearch (Dir_name, Partten): G=Os.walk (dir_name) Res= {"",} forIinchg: forJinchI[-1]: File_path= I[0] +"\\"+J with Open (File_path) as F: forLineinchF:ifPartteninchLine:res.add (File_path) forLineinchRes:ifLine :Print(line) search ("c:\\test","python") using generators to handleImportOSdefFirstnext (func):defWrapper (*args, * *Kwargs): G= Func (*args, * *Kwargs) Next (g)returngreturnwrapper @firstNextdefSearch (target): whileTrue:dir_name=yieldg=Os.walk (dir_name) forIinchg: forJinchI[-1]: File_path= I[0] +"\\"+J Target.send (File_path) @firstNextdefopener (target): whileTrue:file_path=yieldwith open (File_path) as F:target.send ((File_path, F)) @firstNextdefCat (target): whileTrue:file_path, F=yield forLineinchF:target.send ((File_path, line)) @firstNextdefgrep (Partten, target): whileTrue:file_path, Line=yield ifPartteninchline:target.send (file_path) @firstNextdefprinter (): whileTrue:file_path=yield Print(File_path) G= Search (Opener (Cat (grep) ("python", Printer ())))) G.send ("c:\\test")
Three. List-generated, generator-expression
The specific form of a list-generation
List = [process variable form list element for loop if judgment for Loop 2]
Equivalent to
The For loop if determines the for loop element = Expression list. Append (Element)
The builder expression is a list-generated bracket-programmed parenthesis
One of the generators is obtained
You can quickly generate a list by using list (the generated generator)
python\ List and builder expressions