Python Generators (generator) -- yield keyword

Source: Internet
Author: User
Python Generators (generator)

GeneratorIs such a function, it remembers the position in the function body in the last return. The second (or NTH) Call to the generator function jumps to the center of the function, while all local variables in the last call remain unchanged.

The generator not only "remembers" its data status, but also "remembers" its position in the flow control Constructor (in imperative programming, this constructor is not just a data value.

Generator features:

The generator is a function and its parameters are retained.

During iteration to the next call, all the parameters used are reserved for the first time, that is, they are retained when all function call parameters are called for the first time, rather than newly created

In python, yield is such a generator.

Yield generator running mechanism:

When you ask the generator for a number, the generator will execute until the yield statement appears.

The yield parameter is provided to you, And the generator will not continue to run. When you ask him for the next number, he will go from the last status. Run until the yield statement is displayed. Give the parameter to you and then stop. So repeatedly
Until you exit the function. (Here is a simple example of yield)

Yield usage:

In python, When you define a function and use the yield keyword, this function is a generator and its execution will be different from other common functions, the function returns an object instead of your normal
The return statement is used to obtain the result value. To obtain the value, you must call the next () function, for example:

C = h () # h () contains the yield keyword # Return Value c. next ()

Every time the next function of the iterator is called, when the generator function runs to yield, the value after yield is returned and paused at this place, all the statuses will be kept, wait until the next function is called or an exception loop is triggered to exit.

Next, let's take a look at the following example code to illustrate the yield operating mechanism.

def fib(max):    a, b = 1, 1    while a < max:        yield a #generators return an iterator that returns a stream of values.        a, b = b, a+b

Program running:

for n in fib(15):    print n

From the preceding Running Mechanism description, we can know that when the program runs to yield, it will not continue to be executed. ReturnsContains all parameters of the current functionStatus iteratorObject. The purpose isWhen the second call is called, all the parameter values that can access the function are the values of the first access, rather than re-assigning values.

When the program is called for the first time:

Def fib (max): a, B = 1, 1 while a <max: yield a # at this time, the values of a and B are respectively. Of course, the program is also executing at this time, returns a, B = B, a + B

The second call of the program:

As we can see from the above, when we call the first call, a, B =, then we call the next () method of the iterator object returned for the first time ), the program jumps to the yield statement,

Execute the statements a, B = B, a + B, and the value changes to: a, B = 1, (1 + 1) => a, B = 1, 2

The program continues the while loop. Of course, when the yield a statement is run again, it is also like the first time, saving the status of all the parameters of the function and returning an iterator object containing the status of these parameters.

Wait for the third call ....

def fib(max):    a, b = 1, 1    while a < max:        yield a         a, b = b, a+b

Through the above analysis, the detailed operation process of yield can be displayed one by one!

By using the generator syntax, you can avoid the tedious code of writing the iterator class. For example, the above example is implemented using the iteration class. The Code is as follows:

class Fib:    def __init__(self, max):        self.max = max    def __iter__(self):        self.a = 0        self.b = 1        return self    def next(self):        fib = self.a        if fib > self.max:            raise StopIteration        self.a, self.b = self.b, self.a + self.b        return fib

Other yield examples: Arrangement and combination

# Generate a full Arrangement

def perm(items, n = None):    if n is None:        n = len(items)    for i in range(len(items)):        v = items[i:i+1]        if n==1:            yield v        else:            rest = items[:i] + items[i+1:]            for p in perm(rest, n-1):                yield v + pdef comb(items, n = None):    if n is None:        n = len(items)    else:        for i in range(len(items)):            v = items[i:i+1]            if 1 == n:                yield v            else:                rest = items[i+1:]                for c in comb(rest, n-1):                    yield v + c

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.