Python yield USES method examples

  • 2020-04-02 13:14:45
  • OfStack

1. The iterator
The simplest example of a regenerator would be array subscripts, and here's the c++ code:


int array[10];
for ( int i = 0; i < 10; i++ )
    printf("%d ", array[i]);

The stack works in a container (array[10]), which takes the values (array[I]) out of the container in a certain order (I ++) and operates on them (printf("%d ", array[I]).

The above code translates to python:

 


 array = [i for i in range(10)]
for i in array:
    print i,
 

First, array is a container as a list, and second, list, the built-in type, has a default next behavior. The secret action python takes after discovering this is to take out the array container's regenerator, and from there, next gives the value to I for the body of the for loop. For prints the value.

Now the question is can the data do container iteration, can the code?

2. The constructor

How do I turn a function into a constructor?   You just have yield in the body of the function!


def gen():
    print 'enter'
    yield 1
    print 'next'
    yield 2
    print 'next again'
for i in gen():
    print i

With all of you! Python sees yield in the gen function and knows that it can use next. The question is how to play next with the code container?
When we get the iterator out of the container it's nothing, it's at the entrance to the container, which is minus one for the array, and it's at the entrance to the function, which is nothing but next.
Start with for I in g, next let itreator crawl to where the yield statement exists and return the value,
Next then climbs to where the next yield statement exists and returns the value, and so on, until the function returns (at the end of the container).
You can see that the output of the above code is:
enter
1
next
2
Next again

3. The use of yield
The code iteration capability of yield not only interrupts the execution of the function but also takes down the data at the breakpoint and returns it to the next book,
That's what a recursive function needs.
For example, middle order traversal binary tree:
(I think it was written by David Mertz)


def inorder(t):
    if t:
        for x in inorder(t.left):
            yield x
        yield t.label
        for x in inorder(t.right):
            yield x
for n in inorder(tree)
    print n


Related articles: