If the list element can be inferred from an algorithm, then we do not have to create a complete list, thus saving a lot of space.
In Python, this side loop computes the mechanism, called the Generator (Generator).
for in range (ten)]>>>1, 4, 9, +, (+), +, +, Bayi]
for in range (+)>>> g<generator object <genexpr> at 0x104feab40>
List deduced for list
G is the generator that can be called by next (g), with more elements thrown stopiteration errors.
You can also iterate through the For I in G:
Output type
def fib (): = B, A +b while B <: yield b = b, a+ = fib () c12/> #此时, A is a generator
For I in A:
Print (i)
function, the yield is interrupted and the next execution continues until no yield statement can be executed, throwing an exception.
Receive input type
def reciver (): while True: = (yield) print"Got%s" % N
= Reciver () Next (R) r.send (1) r.send ('2')
Input/Output Type
def get (): = 0 = None while True: = (yield result) = n*10= Get () Next (t) for in range: Print (T.send (str (i))) T.close ()
Passing parameters
defcountdown (N):Print("counting down from%d"%N) whilen >0:yieldN N-= 1C= Countdown (10)PrintNext (c)PrintNext (c) forIinchCountdown (10): print (i)PrintSUM (Countdown (10))
The function must be executed before the next() data can be sent, if you forget it will be an error.
What about this? Automatic execution with adorners:
defCoroutine (func):defStart (*args,**Kwargs): G= Func (*args,**Kwargs) Next (g)returngreturnStart@coroutinedefreciver (): whiletrue:n= (yield) Print "Got%s"%nr=reciver () r.send (1) R.send ('2')
Python--Generator