Python List Builder and generator

Source: Internet
Author: User
Tags python list

List Builder is a very simple but very powerful built-in python.

Generate a list [1,2,3,4] can use list (range (1,5))

Application of List Builder

If the above formula is judged, you can filter out the desired result, such as just the square of the even number

Using multi-layer loops



Generator

The essential difference between a generator and a list generator is that one has generated data, and when used, it generates a memory overflow if the data is too large and generates data only when the generator is a loop.

The difference between a generator and a list generator is that one is [], one is ()

Generator Write

g= (x x ()) (g)

The way to print generator is next (g) and for loop


Print the Fibonacci sequence in the form of a function

(max): Nab=n < max: (b) ab=ba+b N=n+fib ()

The above function and generator are only a step away, to turn the FIB function into generator, simply change print (b) to yield to

(max): Nab=n < max:b ab=ba+b N=n+fib ()


To print the generator method for FIB

I fib (): (i)

If you call generator with a For loop, you want to get the return value, you need to capture the stopiteration error, and the return value is contained in the value of stopiteration:

G=FIB (6)

(max): Nab=n < max:b ab=ba+b N=n+g=fib ():: x= (g) (x) E: (E.value)


Python List Builder and generator

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.