Python generator-lazy to beat, but very economical

Source: Internet
Author: User

The generator is characterized by working half-time, stopping to watch others work until someone kicks his butt, and it continues to work. The essence of this function is to use yield.

The generator is a special iterator, so let's start by understanding what an iterator is. We all know the famous Fibonacci series: 1, 1, 2, 3, 5, 8, 13, 21, 34 ... Starting with the third number, each number can be summed up by the two numbers in front of it, which is an iterative process. Obviously, this is a series of non-convergence, we can not use the list or let the collection to extract them once. At this time, if we encapsulate such an iterative process as an iterator, it will only iterate once when it is called, and only keep the current iteration results, so that the program can run faster and will not be a serious burden on memory. Iterators can represent an infinitely large stream of data, or a finite stream of data.

From a code point of view, all objects that can be called by the next () function and return the next value continuously are called iterators:Iterator. a concept similar to iterators is an iterative object (iterable), where objects that can be traversed by a for loop are iterative objects such as list, Dict, and Str. However, these objects are not iterators, which have been explained in the previous paragraph from the characteristics of iterators, and no longer repeat them. However, there is no absolute, through the ITER () function, you can turn them into iterators.

Thus, we can build such a Fibonacci sequence generator:

1 defGenerate ():2A,b,c = 0,0,13      whileA < 20:#a used to count4 5B,c = C,b +c#Iterative Formulas6A = a + 17         yieldC8     return "Fault"  #return value On Error9 Ten  Oney = Generate ()#produces a generator object, but does not call the builder A  forIinchRange (13):#called 13 times -     Print(Y.__next__())#Call the builder using the next () method

The effect of yield is to have the generator suspend execution here and execute the next program instruction. When the next () function is called, the generator continues execution from where it was paused. Once, each call yields a value that calls 13 times to produce 13 values, as shown in

This type of generator does not require parameters, and we need to use the Send () function when we need to pass parameters to the generator, because the next () function does not have this function. Look at the following piece of code:

1 defSing (word1):2     Print(word1)3      whileTrue:4Word2 =yield  #The generator stays here every time it is called5         Print(WORD2)6 7 8A = Sing ("now through the world")9A.send (None)#can be replaced by a.__next__ ()TenA.send ("Linger")

The above code, if not the while loop, there is no way to make every call to the results of the program to stay here, but after the execution of print (WORD2) ended, which makes the program error. The first time we use a generator that needs to pass parameters, we can't pass the parameters we want to pass directly using the Send () function, because the function stops at Yeild and does not need to have this parameter. So we can use the next () function to make the first call, and then call Send () to pass the parameter and invoke it. Of course, if we want to implement the first call with the Send () function, we should pass an empty argument. The results of the operation are as follows:

At this point, it's done!

Python generator-lazy to beat, but very economical

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.