What are generators in python? What are generators used for?

乌拉乌拉~
Release: 2018-08-22 16:18:00
Original
5212 people have browsed it

In the following article, we will learn about what is a generator in python. Understand what python generator is, and what rolegenerator can play in pythonprogramming.

What is a python generator?

With list generation, we can directly create a list. However, due to memory constraints, the list capacity is definitely limited. Moreover, creating a list containing 1 million elements not only takes up a lot of storage space, but if we only need to access the first few elements, the space occupied by most of the subsequent elements will be wasted.

So, if the list elements can be calculated according to a certain algorithm, can we continuously calculate subsequent elements during the loop? This eliminates the need to create a complete list, thus saving a lot of space. In Python, this mechanism of looping and calculating at the same time is called a generator: generator.

To create a generator, there are many ways. The first method is very simple. Just change the [] of a list generation to () to create a generator:

>>> L = [x * x for x in range(10)]
>>> L
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
>>> g = (x * x for x in range(10))
>>> g
<generator object <genexpr> at 0x1022ef630>
Copy after login

After we create a generator, we use a for loop to iterate over it and don't need to worry about StopIteration errors.

generator is very powerful. If the calculation algorithm is relatively complex and cannot be implemented using a for loop similar to list generation, you can also use a function to implement it.

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

def fib(max):
    n, a, b = 0, 0, 1
    while n < max:
        print(b)
        a, b = b, a + b
        n = n + 1
    return &#39;done&#39;
Copy after login

Note that the assignment statement:

a, b = b, a + b
Copy after login

is equivalent to:

t = (b, a + b) # t是一个tuplea = t[0]b = t[1]
Copy after login

, but the temporary variable t can be assigned without explicitly writing it out.

The above function can output the first N numbers of the Fibonacci sequence:

>>> fib(6)112358&#39;done&#39;
Copy after login

If you look closely, you can see that the fib function actually defines the calculation of the Fibonacci sequence. Rules can start from the first element and calculate any subsequent elements. This logic is actually very similar to the generator.

In other words, the above function is only one step away from the generator. To turn the fib function into a generator, just change print(b) to yield b:

def fib(max):
    n, a, b = 0, 0, 1
    while n < max:        yield b
        a, b = b, a + b
        n = n + 1
    return &#39;done&#39;
Copy after login

This is another way to define a generator. If a function definition contains the yield keyword, then the function is no longer an ordinary function, but a generator:

>>> f = fib(6)
>>> f<generator object fib at 0x104feaaa0>
Copy after login

Here, the most difficult thing to understand is that the execution flow of generator and function is different. Functions are executed sequentially and return when encountering a return statement or the last line of function statements. The function that becomes a generator is executed every time next() is called, returns when encountering a yield statement, and continues execution from the yield statement returned last time when executed again.

The above is all the content described in this article. This article mainly introduces the knowledge related to the generator in python. I hope you can use the information to understand the above content. . I hope what I have described in this article will be helpful to you and make it easier for you to learn python.

For more related knowledge, please visit the Python tutorial column on the php Chinese website.

The above is the detailed content of What are generators in python? What are generators used for?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!