Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Generator in python-- yield

2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/03 Report--

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.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report