The yield generator in Python is detailed

Source: Internet
Author: User
Tags generator

#原创, please contact us first.

Before you can learn the builder, you must understand the iterator first. Because the generator is a special kind of iterator , and the generator is more elegant.

An explanation of the iterator can refer to my other blog post: www.cnblogs.com/chichung/p/9537969.html

Let's start with a relatively simple generator, and slowly realize what a generator is.

#List-generatedL = [x forXinchRange (5)]Print(L)#a simple generatorG = (x forXinchRange (5))#g is a generator, also an iterator, and an iterator is an iterative object, so this g can also be an iterative object .Print(Next (G))Print(Next (G))Print(Next (G))Print(Next (G))Print(Next (G)) output: [0,1, 2, 3, 4]01234

Changing the list generator's [] to () becomes a simple generator. From the above example, we can probably know that the generator is an iterator that takes the data out of one, which can reduce the burden of memory.

So what is yield again? Why does he say he's classy?

When we write the result of the output of the code, want to come out one by one. There are two common ways to do this:

Method 1. We can create an iterator class, then write the code into the class, use the class to create an iterative object, and then use the next () function to iterate over the result.

Method 2. We can use the appropriate location of the code function to add yield, this time the function becomes a generator, no need to create an iterator class, no need to write __iter__,__next__ method. This is not very convenient, very elegant? haha haha ~

Accreditations, here are 2 ways to do it, let you understand:

We do a Fibonacci sequence generator. The first number of the Fibonacci sequence is 0, the second number is 1, the third number is the first to second number, and the fourth number is the second to third number added ...

Method 1:

classfeiboiterator ():def __init__(self): SELF.A=0 self.b= 1def __iter__(self):return Selfdef __next__(self): num=SELF.A self.a,self.b= self.b,self.a+self.breturnNumiterator=Feiboiterator ()Print(Next (iterator))Print(Next (iterator))Print(Next (iterator))Print(Next (iterator))Print(Next (iterator))Print(Next (iterator))Print(Next (iterator))Print(Next (iterator)) output:
01235813

Is it a lot of trouble? Also initialize, and write __iter__ and __next__ Rubik's Cube method.

Method 2:

defFeibo (): a=0 B= 1 whileTrue:yielda # If the yield is followed by a data, the data will be returned as the next () function or for ... Iteration of the next value, a, b= b,a+Bgenerator=Feibo ()Print(Next (generator))Print(Next (generator))Print(Next (generator))Print(Next (generator))Print(Next (generator))Print(Next (generator))Print(Next (generator))Print(Next (Generator)) output: 011235813

See! Only 6 lines of code, is not very elegant? How does this program work? How does yield work? We'll tell you what we need to pay attention to now:

1. The red Word of the above code there! If the yield is immediately followed by A data, the data will be returned as the next () function or for ... in ... The next value to iterate over.

2. If there is yield in the function, it is no longer a function. It's a function that returns to the generator! Attention! is to return, this function is not a generator. (fix: This sentence found that there is an error, this function is also a generator)

3. Once you get the generator for the function, you can get the next value with the next () function, just like the iterator.

Well, it's time to understand how yield works!

1. The first time the generator is awakened, it starts at the beginning of the function and, until yield is encountered, suspends the function and suspends the function.
2. The second time the generator is awakened, it starts at the yield breakpoint until yield is encountered.
3. When the generator has no yield and then uses next, the Stopiteration exception is thrown.

Then, let's take a look at the code written in yield above.

The first time you wake the generator with Next (), run from the beginning of the function, encounter yield A, return a, pause the function, and remember that the function is running to this location.

The second wake-up generator, starting at the yield a breakpoint, and then a A, a, a, a and a A, and then a A, a and a, a, and then a loop to a, then pause the function, and remember that the function is running to this location.

This is the reason for how many times it is awakened, but since this function is a dead loop, there is no yield and no stopiteration exception is thrown.

--------------------------------------------------------------------------------------------------------------- --------------------------------------------------------------------------------------------------

In fact, yield can also accept the value, with the Send method to pass in. Code experience:

defGG (): I= 1 whileTrue:recv=yieldIPrint("to receive a value:", recv) I+ = 1Generator=GG ()Print(Next (generator))Print(Generator.send ("456"))Print(Generator.send ("789") ) Output:1to receive a value:4562to receive a value:7893

The implementation process is the same as the example above.

To understand thatyield = A, it returns a.

b = yield, which assigns the value received by yield to B.

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.