Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

Generator in python-- yield

Shulou Source: shulou.com Published: 2022-06-03 04:12:12 10月14日 Update

The Python generator is a powerful thing, especially after the python3.0 version. Let everyone quickly understand the generator in the simplest way.

1. Normal way of writing

Let's take a look at an example, for example, outputting a list of custom lengths is generally written as follows:

The parameter passed in here is 10, so you get a list of 10 elements:

When I pass in 10W, the generated list is very large and takes up memory, and running scripts also takes up cpu.

2. Improved writing method

Improve the code and write it as an iterative class:

Here, self.b records the location of each execution of the next method, and knows how many times the next method is executed each time, so the execution ensures that each output is the desired value. In fact, this is the iteration, and the running state of the function is recorded every time the function is run. The value is returned only when it is called, otherwise it will be in a state waiting to be called.

Running result:

So this improved code solves the problem of resource consumption when you enter 10W, because after entering 10W, the value is returned only when the next function is called, not a large list at a time.

3. Generator

So the code in the second step is too much compared to the first step, so here comes the generator.

Then improve the code:

Just change the code a.append (n) in the first step to yield n, which is a generator, and then call the generator's value through the for statement.

Any function with a yield statement is a generator. When you call this function directly, the internal code will not be executed. Only by calling the next function in yield will the code be executed. The for loop will automatically call the next function to output the value.

It can be understood that a function is interrupted by yield, and when the download is called again, it continues to execute the code from the location of the last interrupt and returns a value.

It's relatively simple. I don't know if you understand it or not.

Tags: Generation code generator function time run output location writing that is method state statement input iteration powerful large primary function thing that is Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Microsoft Apple Shulou Technology Shulou Tech Info Docker