Python Builds and generators

Source: Internet
Author: User

One, generators and generators

1, List-generated

MyList = [I*i for  I in range (3) if i>1]print (mylist)                    run Result: [4]

You can find that the expression for the quick list is generated, for loop range (3), and if I is greater than 1, multiply it by yourself and then output.

2, generator

Mygenerator = (i*i for I in range (3)) print (mygenerator)                Run Result: <generator object <genexpr> at 0x000001fb08f18 Ba0>

You can see that this generator and the list generation are very similar. Just above is [] and the following is ().

This reminds me of the range and Xrange2 functions in Python2. Range is the output of a list, and xrange generates a generator . The generator needs to use a for loop to take a value.

The benefit of the generator is that you can save memory by not having to store values in memory at once, and then calling them when you use them.

Two, yield (for creating generators)

Yield and return are very similar, and return returns only one value, and yield can output multiple values. Yield can also be understood as a return with a memory function.

Def fun1 (): For    I in range (1,5):         print (i)        def fun2 (): For    I in range (1,5):        return I def fun3 ():     F or I in range (1,5):        

  

Calling the FUN1 () function outputs the 1,2,3,4,5

Call fun2 () function output is 1 (execution to return on Exit Function)

Call FUN3 (the 0 function outputs the generator and needs to be taken out using a for loop.)

The FUN3 function and the FUN2 function are compared, the FUN2 function wisdom returns 1 and then exits the function, and yield will know that it has already output the last value the next time it enters the function, so it will return the next value. Essentially executes the next () function (Python2 version)

Description: The generator created by yield is live, and you can change it when you say it with a for loop.

Python Builds and generators

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.