Tag: Wake func Print font while RET BSP time consumption
List Builder:
[I*2 for I in range (10)] This is not a generator.
[Func (i) for I in range (10)]
(I*2 for I in range (10)) This is the generator.
An algorithm, a function, can generate data on the edge of the loop, in order to save space, only the call will generate the corresponding data.
Only the __next () __ Method
You can also use a function to create a generator.
def fib (max):
N,a,b = 0,0,1
While n < max:
Print (b)
A, B = b,a+b
n = n + 1
Return ' Done '
FIB (10)
def fib (max):
N,a,b = 0,0,1
While n < max:
Yield (b)
A, B = b,a+b
n = n + 1
Return ' Done '
Print (FIB (10))
Fib_gen = fib (100)
Print (fib_gen.__next__ ())
Print (fib_gen.__next__ ())
Print (fib_gen.__next__ ())
Catch of exceptions
DefFIB (max):
NA, B =0,0,1
While n < max:
Yield (b)
A, B = b, A+b
n = n +1
Return' Done '
Print (FIB (10))
Fib_gen = FIB (10)
Print (Fib_gen.__next__ ())
Print (Fib_gen.__next__ ())
Print (Fib_gen.__next__ ())
Print (Fib_gen.__next__ ())
Print (Fib_gen.__next__ ())
print (Fib_gen.__next__ ())
print (Fib_gen.__next__ ())
print (Fib_gen.__next__ ())
print (Fib_gen.__next__ ())
while True:
try:
Print (Fib_gen.__next__ ())
except stopiteration as e:
print (" Generator return value: ",e.value"
Break
You can do that.
DefFIB (max):
NA, B =0,0,1
While n < max:
yield (b)
A,b = B,a+b
N = n + 1
return Span style= "COLOR: #6a8759" > ' done '
print (fib (10))
Fib_gen = fib (10)
while True:
try:
print (Fib_gen.__next__ ())
except stopiteration as e:
print (,e.value"
break
Producers and consumers
Import time
DefConsumer (name):
Print"%sReady to eat buns"%name)
While True:
Baozi = yield
print (" bun [%s] came, was [%s] ate!" "% (Baozi, name))
c = Consumer ("Roger")
C.__next__ ();
Baozi = " Meat Buns "
C.send (Baozi)
Send wakes up the generator and gives yield a reference
__next () Just wakes generator, goes to yield, interrupts, returns
Go on
Import time
DefConsumer (name):
Print"%sReady to eat buns"%name)
While True:
Baozi =Yield
Print"Buns[%s]Came, was[%s]Eat It!"% (Baozi, name))
c = Consumer ("Roger")
C.__next__ ();
Baozi ="Meat Buns"
C.send (Baozi)
DefProducerName):
c = Consumer (' A ')
C2 = Consumer ( ' B ')
C.__next__ ()
C2. __next__ ()
print ( " I'm starting to make buns. "
For i in range (10):
Time.sleep (1)
print ( " did 2 bun ")
C.send (i)
C2.send (i)
producer ( "Alex")
Generators can be implemented, single-threaded parallel effects
Ctrip
Python Exceptions and generators