Builder basis

First, demand

  Want to print "print% s of times"% d from the format, the printing at this time has been 2,000,000. (Direct range (2000000) get stuck, do not want the card)

Second, the definition of generator

  1. The generator also iterators in fact derived, wrote a generator, you can save memory to a great extent.

  2. The function uses the yield.

  3.yield: effectiveness and return about the same, but can not appear together and return, after a yield return value, function execution to stay in place does not move. The return will stop, the next call will come again.

Third, examples

DEF PrintX ():
     for I in Range (2,000,000 ):
         the yield  ' X = S% ' % I 

G = PrintX () 
G1 = PrintX ()            # This is a two generators 
                 #g .__ next __ (): Get a
count = 0 for i in G: Print (i)        # while adjusting the print side. While generating a data processing side. + =. 1 count IF count> 50:     # any time plus the count value, can be taken by the next BREAK Print ( ' *** ' , G. __next__()) #*** x=51

  When where, g = printx (), does not actually create a range (2000000), while in the lower printing only from memory, generating a return data a.


Fourth, the introduction of several functions:

__iter __ (): This method illustrates There may iteration.

__next __ (): This method is described there may be taken out one by one.

__setstate __ (): You can specify the location from which to start taking.

__add __ (): When using addition, in fact, to call __add__ machine translation method.

 (Double under the direct method is rarely invoked, usually with other grammar trigger)

 

V. Summary

  1. The generator is essentially an iterator

  2. The forms generator

    1) generator function

    2) generator expression

  3. The generator function: generator function is a function containing the yield keyword.

  4. The generator function features:

    1) After the called function does not perform the function returns a generator.

    2) After calling method will __next__ to take a value. Take complete until after the last error.

  The values ​​from several ways Builder:

    1)next

DEF Generator ():
     for I in Range (20000000 ):
         the yield  " Print% s of times " % (I + 1 ) 

G = Generator ()
 Print (G. __next__ ())     # print 1st

       2)for

def generator():
    for i in range(20000000):
        yield "打印第%s次"%i
        
g=generator()
num=0
for i in g:
    num+=1
    if num>50:
        break
    print(i)

    3) Data type cast

DEF Generator ():
     for I in Range (20 is):    # data is small, 
        the yield  " print% s of times " % (I +. 1 ) 

G = Generator ()
 Print (List (G))         # the generator is converted to list, while the data in memory. (Total memory)

 

  

Guess you like

Origin www.cnblogs.com/lowislucifer/p/10993723.html
Recommended