Python generator usage

Generator , under certain circumstances, you can save a lot of space

such as:

>>> b = (x for x in range(10))

>>> b

<generator object <genexpr> at 0x02A17120    > This is a generator,

Occupy memory space is much smaller than the list

Required value, it can be used next () function , or the __next __ () method, such as taking the above b values:

>>> next(b)

0

>>> b.__next__()

1

>>> next(b)

2

>>> b.__next__()

3

>>>……

PS : of course also be used for traversing b value

 

Generating another's seed writing and Applications:

Fibonacci column is to say a number back is always in front and two numbers , such as: 1,1,2,3,5,8,13,21 ...... , you can use the following way to create such a group number:

def createNum():

        print("start----------------")

        a,b = 0,1

        for i in range(5):

# As long as the function inside yield keyword, it means that this function is a generator

                yield b               

                a,b = b,a+b

        print("stop--------")

a = createNum()

 

Go for the first time the Next (A) , above, perform the function of steps :

1,  the implementation of print ( "start ----------------")

2、 a = 0, b = 1

3,  the first cycle, walked yield b , print a b out, the current is 1 , encountered yield , the program will stop down run

4,  take the second Next (A) , program execution continues from just stopped position yield b following the start, is performed : A, B = B, A + B , case B = = 0 +. 1. 1 , and a second for loop , again performed to the yield b , print b the value 1 , and again stopped.

5,  again go Next (A) , repeat the above steps, the print 2 out

6,  until the for loop is completed, go again next (a), throws an exception: StopIteration

 

The effect generator means that you can pre- define a possible life as a very Duofei Bo Fibonacci series a function of the value of this function is very small footprint, the need for a time, and then with the next function to generate , need how many on next how many times

 

 

Further, there is a case to be complete cross call two functions:

def test1 (): # define a with a yield None of the generator

while True:

print(“----111------”)

yield None

 

def test2 (): # define another with a yield None generator

while True:

print(“----222------”)

yield None

 

a = test1 () # create two objects generators

b = test2()

def test (): # define a function call to generate object

while True:

a.__next__()

b.__next__()

 

test()

 

The results :

----111------

----222------

----111------

----222------

----111------

----222------

----111------

----222------

……

 

Guess you like

Origin www.cnblogs.com/sy-zxr/p/12054052.html