Python tutorial 6 -- Python 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 you 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, such a mechanism for looping and computing is called generator.
There are many ways to create a generator. The first method is very simple. You only need to change [] of a list generator type to (), and a generator is created:
>>> 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
at 0x7f8aaa2bbaf0>
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 the list directly, but how can we print every element of generator?
To print them one by one, you can use the next () function to obtain the next return value of generator:
>>> next(g)0>>> next(g)1>>> next(g)4>>> next(g)9>>> next(g)16>>> next(g)25>>> next(g)36>>> next(g)49>>> next(g)64>>> next(g)81>>> next(g)Traceback (most recent call last): File "
", line 1, in
StopIteration
As we will go through, generator stores algorithms. Every time next (g) is called, the value of the next element of g is calculated until the last element is computed, when no more elements exist, the StopIteration error is thrown.
Of course, it is inconvenient to call next (g) continuously. Use the for loop when the correct method is used, because generator can also iterate the object:
>>> g = (x * x for x in range(10))>>> for n in g:... print(n)... 0149162536496481
Therefore, after we create a generator, we will never call next (), but iterate it through the for loop without worrying about the StopIteration error.
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 Fibonacci series (Fibonacci), apart from the first and second series, 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:
def fib(max): n, a, b = 0, 0, 1 while n < max: print(b) a, b = b, a+b n = n + 1 return print('done')
The above function can output the first N of the Fibonacci sequence:
fib(6)
As we can see from a closer look, 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:
>>> def fib(max):... n, a, b = 0, 0, 1... while n < max:... yield b... a, b = b, a+b... n = n+1... return 'done'... >>> f = fib(6)>>> f
This is another method for defining generator. If a function definition contains the yield keyword, this function is no longer a common function, but a generator.
The most difficult thing to understand here is that the execution process of generator and function is different. The function is executed sequentially. If a return statement or the last row of the function statement is returned.
The generator function is executed every time next () is called. When the yield statement is returned, the yield statement returned last time is executed again. <喎?http: www.bkjia.com kf ware vc " target="_blank" class="keylink"> VcD4NCjxwPr7ZuPa88rWltcTA/examples/dfWMaOsM6OsNaO6PC9wPg0KPHByZSBjbGFzcz0 = "brush: java;"> >>> def odd():... print('step 1')... yield 1... print('step 2')... yield(3)... print('step 3')... yield(5)...
When calling this generator, you must first generate a generator object, and then use the next () function to continuously obtain the next return value:
>>> o = odd()>>> next(o)step 11>>> next(o)step 23>>> next(o)step 35>>> next(o)Traceback (most recent call last): File "
", line 1, in
StopIteration
We can see that odd is not a common function, but a generator. During the execution process, yield is interrupted and the next execution will continue. After three times of yield execution, no yield can be executed. Therefore, if you call next (o) for the first time, an error is returned.
Back to the fib example, we call yield continuously in the loop process, and it 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.
>>> for n in fib(6):... print(n)... 112358
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:
>>> g = fib(6)>>> while True:... try:... x = next(g)... print('g', x)... except StopIteration as e:... print('Generator return value:', e.value)... break... g 1g 1g 2g 3g 5g 8Generator return value: done
For details about how to capture errors, the subsequent error handling will be explained in detail.
Summary
Generator is a very powerful tool. In Python, you can simply change the list generator type to generator, or implement a complex logic generator through functions.
To understand the working principle of generator, it is to constantly calculate the next element in the for loop process and end the for loop with appropriate conditions. For the generator to which the function is changed, if you encounter a return statement or execute the last row of the function body, the command of the generator is ended and the for loop ends.
Note that common functions and generator functions are differentiated. Common function calls directly return results:
>>> r = abs(6)>>> r6
The "call" of the generator function actually returns a generator object:
>>> g = fib(6)>>> g
Small exercises
The Yang Hui triangle is defined as follows:
1 1 1 1 2 1 1 3 3 1 1 4 6 4 11 5 10 10 5 1
Think of each row as a list and try to write a generator to continuously output the list of the next row: