The yield python popular understanding

I, understand yield, first step is to understand the difference between yield and return of

Print ( ' the yield: ' )
 DEF _testyield ():
     for I in Range (. 5 ):
         the yield I * I
 # generated here builder object, with the same meaning as java object 
Generator = _testyield ()

for i in range(5):
    print(next(generator))
#-----------------------------------------------------------#
Print ( ' return: ' ) DEF _RETURN (n-): # Here is res a list [], the result is [1,2,3,4,5] res = [I I * for I in Range (n- )] return RES for i in _return(5): print(i)

And return the results of the above yield the same generation:

But the difference there is that:

return return is a list of lists, and each call yield return only one value, no doubt, use return space overhead is relatively large, especially when operating a huge amount of data, operating a large list of time will cost more harm than good

 

II, yield implementation

def foo():
    print("starting...")
    while True:
        res = yield 4
        print("res:",res)


G = foo ()
 # At this time any information is not printed, the generator object description is generated, the function is not performed

Print ( ' - ' * 30 )
 Print ( ' G_1 ' , Next (G))
 # call next, the function begins execution, and the yield reaches this point, return the generated 4

Print ( " * " * 20 is )
 Print ( ' G_2 ' , Next (G))
 # RES: none, then the instructions are started step, and the second cycle yield reaches this point

print("#"*30)
print('g_3',next(g))

Print results are as follows:

 

 Description:

1, when the function call contains yield, does not perform a function, it generates and returns a generator object

2, the first time a value next taken, will perform a first function the yield, stop

3, when the back next, starts from a yield, then executed, the next cycle to yield

Referring to the third row are behind.

 

III, continue to root yield

foo DEF (): 
Print ( "Starting ...")
for i in the Range (6):
RES = yield 4
Print ( "RES:", RES)

# When we add new yield
for i in the Range (6):
= the yield. 5 RES
Print ( "RES", RES)

G = foo ()
# any case not print information generator object description is generated, the function is not executed

for I in Range (. 7):
Print (Next (G ))

The results are:

 

 The results appear last 5, description will yield the normal order of execution, not reload function

 

Guess you like

Origin www.cnblogs.com/gambler/p/11875575.html