Generator in python)

Source: Internet
Author: User

The generator is a very cool feature in python.
2.2 becomes a part of the standard. In many cases, it allows you to simplify operations related to unbounded (infinite) sequences in an elegant and lower memory consumption mode.

A generator is a special function that can be used as an iterator. Its function implementation relies on the keyword yield. The following is a simple demonstration of how it operates:

>>> Def spam ():
Yield "first"
Yield "second"
Yield "third"

>>> Spam
<Function spam at 0x011F32B0>
>>> For x in spam ():
Print x

First
Second
Third
>>> Gen = spam ()
>>> Gen
<Generator object spam at 0x01220B20>
>>> Gen. next ()
'First'
>>> Gen. next ()
'Second'
>>> Gen. next ()
'Third'

A generator is defined in the function spam (), but the call to spam () can always get a separate generator object, rather than executing the statements in the function. This object (generator object) contains the original code of the function and the status of the function call. The status includes the variable value of the function and the current execution point. The function is suspended at the yield statement ), return the current value and store the call status of the function. When the next item is required, you can call next again to continue the execution from the last stopped status of the function and know the next yield statement.

The main difference between a generator and a function is that the return a value function. The yield a value generator simultaneously marks or remembers a point.
Of the yield allows you to resume execution from the tag point during the next call.yieldConverts a function to a generator, and the generator returns the iterator in turn.

There are three ways to tell the loop generator that there is no more content:

  1. Execute to the end of the function ("fall
    Off the end ")
  2. Use a return Statement (it may not return any value)
  3. Throw a StopIteration exception.

OneClassic exampleIs compared with the static statement in C language: the so-called static variable is not explicitly supported by Python, but when the functions are called each other, the generator allows you to achieve similar results in a more elegant way:

In C Language

Implementation of the fibonacci function:

# Include <stdio. h>

Int main (){
Printf ("0 \ n ");
Printf ("1 \ n ");
While (1)
Printf ("% d \ n", fib ());
/* For test use */
// Int I = 0;
// While (I <20 ){
// I ++;
// Printf ("% d \ n", fib ());}
}

Int fib (){
Static unsigned first = 0, second = 1, next, retval;

Next = first + second;
Retval = next;
First = second;
Second = next;

Return retval;

}

Python implementation:

#! /Usr/bin/env python
#-*-Coding: UTF-8 -*-
# Filename: fib. py

Def fib ():
First = 0
Second = 1
Yield first
Yield second

While1:
Next = first + second
Yield next
First = second
Second = next

Run:

>>> From fib import fib
>>> Fib ()
<Generator object fib at 0xb76fcfcc>
>>> Import itertools
>>> List (itertools. islice (fib (), 10 ))
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]

You can also use the following method to extract a part of the output (but the itemtools module is recommended ):

>>> For (I, num) in zip (range (10), fib ()):
... Print num

Above

The implementation of the fibonacci function seems complicated, and the more simple and elegant implementation is as follows:

#! /Usr/bin/env python
#-*-Coding: UTF-8 -*-
# Filename: fib. py

Def fib ():
First, second = 0, 1
While1:
Yield second
First, second = second, first + second

Note: however, due to the static feature in C, multiple groups must be generated in a function.
The same function, such as fib1 () fib2 () fib3 (), may need to be defined in the fibonacci series. In python, you can use the above functions to construct any number of independent generator objects.

In what aspects should generator be used for better memory saving-you can use the values in the list that need to be calculated, but you only need to access one item at a time, compared with the pre-calculated method to store it in a list, the generator calculates its values one by one (computes the values on the fly) during running ).

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.