Python-Generator/point you don't know, python-generator

Source: Internet
Author: User

Python-Generator/point you don't know, python-generator
1. What is a generator?

By using the list generation method, we can directly create a list. However, due to memory restrictions, the list capacity must be limited. In addition, creating a list containing 1 million elements not only occupies a large storage space, but if we only need to access the first few elements, the space occupied by the vast majority of elements is wasted. Therefore, if the list elements can be calculated by some algorithm, can we continue to calculate the subsequent elements in the loop process? In this way, you do not need to create a complete list to save a lot of space. In Python, this type of computing mechanism is called generator.

2. method 1 for creating a generator

There are many ways to create a generator. The first method is very simple. You only need to change a list-generated [] ()

The difference between L and G is that the [] and () of the outermost layer, L is a list, and G is a generator. We can print every element of L directly, but how can we print every element of G? To print them one by one, you can use the next () function to obtain the next return value of the generator:


Running result:
Running result:

The generator stores the algorithm. Each time next (G) is called, the value of the next element of G is calculated until the last element is computed and no more elements exist, throw a StopIteration exception. Of course, this constant call to next () is too abnormal. The correct method is to use the for loop, because the generator is also an iteratable object. Therefore, after we create a generator, we will never call next (), but iterate it through the for loop without worrying about the StopIteration exception.

Method 2

Generator is very powerful. If the calculation algorithm is complex and cannot be implemented using a for loop similar to the list generation type, you can also use functions.

For example, in the famous onacci series, except for the first and second numbers, any number can be obtained by adding the first two numbers:

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

The Fibonacci series cannot be written in the form of list generation, but it is easy to print it out using functions:


Running result:

After careful observation, we can see that the fib function actually defines the calculation rule of the Fibonacci series. It can start from the first element and calculate any subsequent elements. This logic is very similar to generator.

That is to say, the above functions and generator are only one step away. To change the fib function to generator, you only need to change print (B) to yield B:


Running result:
In the above fib example, we continuously call yield During the loop process, which will be interrupted. Of course, you must set a condition for the loop to exit the loop. Otherwise, an infinite number of columns will be generated. Similarly, after the function is changed to generator, we basically never use next () to obtain the next return value, but directly use the for loop for iteration:
Running result:

However, when you use the for loop to call generator, the return value of the return Statement of generator cannot be obtained. If you want to get the returned value, you must capture the StopIteration error. The returned value is included in the value of StopIteration:


Running result: 3. send

Example: When yield is executed, the gen function is temporarily saved and the I value is returned. temp receives the next c. send ("python"), the value sent by send, c. next () is equivalent to c. send (None)

Use the next Function


Running result:

Use the _ next _ () method


Running result:

Use send

Running result:

4. implement multiple tasks

One of the implementation methods of multi-task simulation: coroutine


Running result:

Summary

A generator is a function that remembers the position in the function body during 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:

1. Memory saving

2. 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

5. iterator

Iteration is a way to access collection elements. An iterator is an object that can remember the traversal position. The iterator object is accessed from the first element of the set until all elements are accessed. The iterator can only move forward without moving back.

1. iteratable objects

There are several types of data that directly act on the for Loop:

One type is set data types, such as list, tuple, dict, set, and str;

The first type is generator, which includes generator and generator function with yield.

These objects that can directly act on the for loop are collectively referred to as iteration objects: Iterable.

2. Determine whether iteration is possible

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


Running result:

The generator can not only act on the for loop, but also be continuously called by the next () function and return the next value until the StopIteration error is thrown to indicate that the next value cannot be returned.

3. iterator

The object that can be called by the next () function and continuously return the next value is called the Iterator: Iterator.


Running result: 4. iter () function

All generators are Iterator objects, but list, dict, and str are Iterable but not Iterator.

You can use the iter () function to convert Iterable, such as list, dict, and str into Iterator:


Running result:

Summary

· All objects that can act on the for loop are of the Iterable type;

· All objects that can act on the next () function are of the Iterator type.

· Set data types such as list, dict, and str are Iterable but not Iterator. However, you can use the iter () function to obtain an Iterator object.

· The purpose is to reduce the occupied content when using the set.

6. Closure

1. function reference


Running result:
Illustration: 2. What is a closure?
Running result: 3. See the actual example of a closure:
Running result:

In this example, the line function and the variables a and B form a closure. When creating a closure, we use the line_conf parameters a and B to describe the values of these two variables. In this way, we have determined the final form of the function (y = x + 1 and y = 4x + 5 ). We only need to transform the parameters a and B to obtain different linear expression functions. As a result, we can see that closures also improve code reusability.

If no closure exists, we need to describe a, B, and x each time we create a linear function. In this way, we need more parameter passing and reduce code portability.

If you have any questions during the learning process or want to obtain learning resources, join the learning exchange group.
626062078. Let's learn Python together!

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.