Python Advanced Tutorial-builder

Source: Internet
Author: User
Tags for in range

Generator (Generator)

With list generation, you can create a list directly. However, the capacity of the list is certainly limited by memory constraints. Also, creating a list of 1 million elements takes up a lot of storage space, and if we just need to access the first few elements, then the vast majority of the elements in the back are wasted.

So, if the list element can be calculated according to an algorithm, can we continue to calculate the subsequent elements in the process of the loop? This eliminates the need to create a complete list, which saves a lot of space. In Python, this side loop computes the mechanism, called the Generator (Generator).

There are a number of ways to create a generator. The first method is simple, as long as a list-generated [] is changed to (), a generator is created:

 for  in range () >>> 1, 4, 9, +, (+), +, +, Bayi]for in Range (Ten)>>> g<generator object <genexpr> at 0x0000000002680948>

The difference between creating L and G is only the outermost [] and (), L is a list, and G is a generator.

I can print out every element of the list directly, but how do we print out every element of generator?

If you want one print out, you can go through the generator Next () method:

>>> G.next () 0>>> g.next ()1>>> g.next ()4>>>  G.next ()9>>> g.next () 16>>> g.next ()

Of course, it's not practical to keep calling the next () method above, and the correct way is to use a For loop because generator is also an iterative object:

 for  in range (+ ))for in G:    print  n    0 149162536496481

So, after we create a generator, we basically never call the next () method, but instead iterate over it with a for loop.

Generator is very powerful. If the algorithm is more complex, it can be implemented using a similar list-generated for loop when it cannot be implemented.

For example, the famous Fibonacci sequence, in addition to the first and second numbers, can be added by the first two numbers in any number:

The Fibonacci sequence is not written in list generation, but it is easy to print it out with a function:

def fib (max):     = 0,0,1     while n < Max:        print  b        = b,a+b        = n+1

The above function can output the number of the first n of the Fibonacci sequence:

FIB (7)11235813

Looking closely, it can be seen that the FIB function is actually defined as the Fibonacci of the tangent sequence of the rule, you can start from the first element, the calculation of subsequent arbitrary elements, this logic is actually very NVC generator.

In other words, the above functions and generator are only a step away. To turn the FIB function into a generator, just change print B to yield B:

def fib (max):     = 0,0,1     while n < Max:        yield  b        = b,a+b        = n+1

Generator is not the same as the execution of a function, the function is executed sequentially, the return statement is encountered, or the last line function statement is returned. The function that becomes generator, executes at each call to next (), encounters a yield statement return, and executes again from the last return yield statement.

For example: Define a generator and return the number 1,3,5 in turn:

>>>defOdd ():Print 'Step1'    yield1Print 'Step2'    yield3Print 'Step3'    yield5 >>> o =Odd ()>>>o.next () Step11>>>o.next () Step23>>>o.next () step35>>>O.next () Traceback (most recent): File"<pyshell#86>", Line 1,inch<module>o.next () stopiteration>>>

As you can see, odd is not a normal function, but a generator, in the execution process, encounter yield is interrupted, the next time continue to execute. After 3 yield, no yield can be executed, so the 4th call to next () error

Back to the FIB example, we constantly call yield in the loop, and then we interrupt, of course, to set a condition for the loop to exit the loop, or it will produce an infinite sequence.

Similarly, after changing a function to generator, we basically never use next () to invoke it, but rather iterate with the For loop:

 for  in fib (6):    print  n    
Summarize

Generator is a very powerful tool, in Python, you can simply change the list generation to generator, or you can implement the generator of complex logic through functions.

To understand how generator works, it calculates the next element in the for loop, and ends the for loop in the appropriate condition, and for the generator that the function changes, it encounters a return statement or executes the last line of the function body. is to end the generator instruction, and the For loop ends with it.

Python Advanced Tutorial-builder

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.