Xi. python generators and iterators

Source: Internet
Author: User

One, List generation: 1, generate a list: lists = [i*2 for i in range]       #使用列表生成式生成一个列表, occupy memory space, when the amount of large can cause a lot of waste. Print (list)  2, using the generator to generate the list: (generator) List1 = (i*2 for me in range)       #将生成列表的公式存在变量中, take it when needed, (Note: The disadvantage is that you can only take the next one) print (list1.__next__ ())                     #使用__next__取数据, take one number at a time and throw a stopiteration error at the end of the fetch for I in list1:               #由于一次一次的取比较麻烦, we can also use the For loop to fetch     print (i)                   3, if you need to calculate the results using the list cannot be generated, we can also use the function to make generators, such as the Fibonacci sequence. Fibonacci sequence: (Fibonacci) Introduction: Fibonacci sequence, which is a number of the first and second numbers, any number can be added by the first two numbers to be implemented by the Python function Fibonacci sequence: def fib (A,b,max):                            # A is the first number of Fibonacci Polachi, B refers to the second number of Fibonacci Polachi, and Max refers to adding a few times     n=0    while n<max:         print (b)         a,b=b,a+b        n=n+1         return ' Done ' fib (10,15,12) If you want to turn the above function into a generator, just change print (b) to yield B to yield: Return the result every time the call to yield, and save the current position, Resumes from the saved location when it is executed again. def fib (a,b,max):    n = 0    while n < max:        yield b        a, B = B, a + b        n = n + 1    re Turn ' done '  f = (fib (10,15,12))                 #将函数指定为一个变量 , the value is evaluated by the variable, otherwise the side pass parameter cannot be taken. Print (f.__next__ ()) print (f.__next__ ()) print (f.__next__ ())  

11, Python builder, and iterator

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.