This says that the biggest benefit of the generator is the ability to save memory space.
Because the generator is generator, it is a single generation of data. During the build process, you can go in and out, and you can do something else. haha ~ ~ ~
On the code: here to plug in a list is called the creation of things, is a sentence to write a list.
This is the simplest list generation, a little bit of a change, it becomes the generator.
See, the only difference is that the list generation is the bracket, and the generator is the parentheses.
A slightly more complex generator can be represented by a function, such as the Fibonacci sequence.
#__*__ coding:utf-8 __*____author__="david.z"deffib (max): N,a,b=0,0,1 whileN <Max:yieldb A, a= B, A +B N= N+1return ' Done'Print(Type (FIB (10)))Print(FIB (10)) F= FIB (10)Print(F.__next__())Print(F.__next__())Print("==========")Print(F.__next__())Print(F.__next__())Print(F.__next__())Print("Start Top". Center (20,"*")) forIinchF:Print(i)
This makes it possible to get in and out, and even better.
For example, eat steamed buns.
defConsumer (name):Print("%s ready to eat buns! "%name) whileTrue:baozi=yield Print("Bun [%s] came, eaten by [%s]! "%(Baozi,name)) C= Consumer ("david.z") c.__next__() B1="Red Bean Stuffing"C.send (B1) c.__next__()
A Send command is referenced here to put a good stuffed bun into the generator.
Finally, implementing a single-threaded implementation of multiple concurrency effect. Also use the generator, which is actually a step-by-step generator.
Import TimedefConsumer (name):Print("%s ready to eat buns! "%name) whileTrue:baozi=yield Print("Bun [%s] came, eaten by [%s]! "%(Baozi,name)) C= Consumer ("david.z") c.__next__() B1="Red Bean Stuffing"C.send (B1) c.__next__()defproducer (name): C= Consumer ("A") C2= Consumer ("B") c.__next__() c2.__next__() Print("Lao Tzu began to prepare buns! ") forIinchRange (10): Time.sleep (1) Print("made 1 buns, in two halves! ") c.send (i) c2.send (i) Producer ("Alex")
The Magical magic of generators