python-Generator/Dot you don't know

Source: Internet
Author: User
Tags iterable

1. What is a generator

With list generation, we can create a list directly. However, with memory limitations, the list capacity is certainly limited. Also, creating a list of 1 million elements takes up a lot of storage space, and if we just need to access the first few elements, the vast majority of the space behind it is wasted. So, if the list element can be calculated according to an algorithm, can we continue to calculate the subsequent elements in the process of the loop? This eliminates the need to create a complete list, which saves a lot of space. In Python, this side loop computes the mechanism, called the generator: Generator.

2. Create a Generator method method

There are a number of ways to create a generator. The first method is simple, just change the [] to () of a list-generated

The difference between creating L and G is only the outermost [] and (), L is a list, and G is a generator. We can print out every element of l directly, but how do we print out every element of G? If you want to print one, you can get the next return value of the generator using the next () function:


Operation Result:
Operation Result:

The generator saves the algorithm, each time it calls next (g), calculates the value of the next element of G, until the last element is computed, and when there are no more elements, the stopiteration exception is thrown. Of course, this constant call to next () is so perverted that the correct approach is to use a for loop because the generator is also an iterative object. So, after we have created a generator, we basically never call next (), but instead iterate over it with a for loop and don't need to care about the stopiteration exception.

Method 2

Generator is very powerful. If the algorithm is more complex, it can also be implemented by using a function that is not possible with a For loop that resembles a list-generated type.

For example, the famous Fibonacci sequence (Fibonacci), except for the first and second numbers, can be summed up by the top two numbers:

1, 1, 2, 3, 5, 8, 13, 21, 34, ...

The Fibonacci sequence is not written in a list, but it is easy to print it out with a function:


Operation Result:

Looking closely, it can be seen that the FIB function is actually a calculation rule that defines the Fibonacci sequence, starting with the first element and extrapolating any subsequent elements, which are actually very similar to generator.

In other words, the above functions and generator are only a step away. To turn the FIB function into a generator, simply change print (b) to yield B:


Operation Result:
In the above Fib example, we constantly call yield during the loop, and we are constantly interrupted. Of course, you have to set a condition for the loop to exit the loop, or it will produce an infinite sequence. Similarly, after changing the function to generator, we basically never use next () to get the next return value, but instead use the For loop to iterate:
Operation Result:

However, when you call generator with a For loop, you find that you cannot get the return value of the generator return statement. If you want to get the return value, you must catch the Stopiteration error, and the return value is contained in the value of stopiteration:


Running Result: 3.send

Example: When executing to yield, the Gen function is temporarily saved, returning the value of I; temp receives the next c.send ("Python"), the value sent by send, C.next () equivalent C.send (None)

Using the next function


Operation Result:

Using the __next__ () method


Operation Result:

Using Send

Operation Result:

4. Achieve multi-tasking

One of the simulation multi-tasking implementations: co-process


Operation Result:

Summarize

The generator is a function that remembers the position of the last time it was returned in the body of the function. A second (or nth) call to the generator function jumps to the middle of the function, and all local variables that were last called remain unchanged.

The generator not only "remembers" its data state; the generator also "remembers" its location in flow control constructs (in imperative programming, this construct is not just a data value).

Features of the generator:

1. Save Memory

2. When iterating to the next call, the parameters used are left for the first time, that is, the parameters of all function calls are preserved the first time they are called, not the newly created

5. iterators

Iterations are a way to access the elements of a collection. An iterator is an object that remembers where to traverse. The iterator object is accessed from the first element of the collection until all of the elements have been accessed and finished. Iterators can only move forward without backing back.

1. Can iterate objects

There are several types of data that are directly acting on a For loop:

A class is a collection of data types, such as list, tuple, dict, set, str, and so on;

A class is generator, including generators and generator function with yield.

These objects that can directly act on a for loop are called an iterative object: Iterable.

2. Determine if you can iterate

You can use Isinstance () to determine whether an object is a Iterable object:


Operation Result:

The generator can not only be used for a for loop, but it can also be called by the next () function and return the next value until the last throw Stopiteration error indicates that the next value cannot be returned again.

3. iterators

An object that can be called by the next () function and continually returns the next value is called an iterator: Iterator.


Run Result: 4.iter () function

Generators are iterator objects, but list, dict, and Str are iterable, but not iterator.

To change the list, dict, str, etc. iterable to iterator you can use the ITER () function:


Operation Result:

Summarize

• All objects that can be used for a for loop are iterable types;

• All objects that can be used for the next () function are iterator types

• Collection data types such as list, dict, str, etc. are iterable but not iterator, but a iterator object can be obtained through the ITER () function.

• The goal is to reduce the amount of content that is consumed when using the collection.

6. Closures

1. Function references


Operation Result:
Illustration: 2. What is closures
Running results: 3. See the actual example of a closure:
Operation Result:

In this example, the function line and the variable A, a and B constitute the closure. When we created the closure, we explained the values of the two variables through the line_conf parameter, a and B, so that we determined the final form of the function (y = x + 1 and y = 4x + 5). We only need to change the parameter, a, B, we can get a different line expression function. Thus, we can see that closures also have the effect of improving code reusability.

Without closures, we need to explain a,b,x each time we create a line function. In this way, we need more parameter passing and less portability of the code.

You are welcome to join the Learning Exchange Group if you encounter any problems or want to acquire learning resources in the learning process.
626062078, we learn python! together.

python-Generator/Dot you don't know

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.