This article mainly introduces the yield and generator of python in detail, and provides an in-depth study of the python generator and yield keywords. For more information, see
Preface
It is hard to say that you will do things you have never used and that you have never understood. Although I have been familiar with the concept of python coroutine before, I am just taking a look at it. During a conversation these two days, when someone asks about the coroutine, I can't remember what I 've seen, later, I suddenly thought of yield, but it was too late. I can only say that the concept is unclear. So this article first gets a glimpse of the python generator and yield keywords.
What is a generator?
1. the generator is a special program that can be used to control the iterative behavior of loops.
2. the generator is similar to a function whose return value is an array. This function can receive parameters and be called. However, unlike normal functions, it returns an array containing all values at once, the generator generates only one value at a time, which greatly reduces the number of inner and crude values, and allows calling a function to quickly start processing the first few return values. Therefore, the generator looks like a function but acts like an iterator.
Generator in python
Python provides two basic methods.
1) generator function: it is also defined by def. The keyword yield is used to return a result at a time, blocking and restarting.
2) generator expression: returns an object that generates results only when necessary.
The following describes in detail.
1. Generator Functions
Why is it called a generator function? Because it generates a numerical queue over time. After a general function is executed, a value is returned and then exited. However, the generator function is automatically suspended and then re-picked up for execution. Then, the function is disabled using the yield keyword, return a value to the caller and retain enough of the Current Status to continue the function execution. The generator is closely related to the iteration protocol. every iteration object has a _ next () _ member method. This method either returns the next iteration, or cause an exception to end the iteration.
To support iterative protocolsYieldThe function of a statement is compiled as a generator. When a function is called, a generator object is returned. The returned object supports iterative interfaces, that is, the member method _ next () _ continues to execute from the break.
See the following example:
# codesdef create_counter(n): print "create counter" while True: yield n print 'increment n' n += 1cnt = create_counter(2)print cntprint next(cnt)print next(cnt)# output
create counter2increment n3
Analyze this example:
- The keyword yield appears in the create_counter function, indicating that this function generates only one result value each time. This function returns a generator (which can be seen through the first line of output) to generate continuous n values.
- When creating a generator instance, you only need to call it like a normal function, but this call does not execute this function. This can be seen through the output.
- The next () function uses the generator object as its own parameter. During the first call, it executes the create_counter () function to the yield statement and returns the resulting value 2.
- We call the next () function repeatedly, and execute it from the last suspended place until the yield keyword is encountered again.
For a deeper understanding, let's take another example.
#codingdef cube(n): for i in range(n): yield i ** 3for i in cube(5): print i#output0182764
Therefore, from the perspective of understanding the function, we can compare yield to return, but the function is indeed completely different. In the for loop, the next () function is called every time the iteration rule is automatically followed, therefore, the above results are not difficult to understand.
2. Generator expression
The generator expression comes from the combination of iteration and list parsing. For more information about the concepts and usage of list parsing, see my previous blog. The generator expression is similar to list parsing, but he uses angle brackets instead of square brackets. The following code:
>>># List resolution generation list >>> [x ** 3 for x in range (5)] [0, 1, 8, 27, 64] >>>>># generator expression >>> (x ** 3 for x in range (5 ))
At 0x000000000315F678 >>># conversion between the two >>> list (x ** 3 for x in range (5) [0, 1, 8, 27, 64]
In terms of operations, it is very inconvenient to use a large number of next () functions in the generator table, and the for Loop will automatically start the next function, so you can use it as follows:
>>> for n in (x ** 3 for x in range(5)): print('%s, %s' % (n, n * n)) 0, 01, 18, 6427, 72964, 4096>>>
Comparison between the two
An Iteration can be written as either a generator function or a coroutine generator expression. Both automatic and manual iterations are supported. These generators only support one active iteration, that is, the generator's iterator is the generator itself.
Summary
I think of what I often say when I was in junior high school. It's better to do it manually.