1. Iterator
The simplest example of an iterator should be an array subscript, and look at the following C + + code:
The code is as follows:
int array[10];
for (int i = 0; i <; i++)
printf ("%d", array[i]);
The iterator works in a container (array[10]), which takes the value (Array[i]) out of the container in a certain order (i++) and operates (printf ("%d", Array[i]).
The above code translates into Python:
The code is as follows:
Array = [I for I in range (10)]
For I in array:
Print I,
First, the array as a list is a container, followed by the list of the built-in type has the default next behavior, Python found that after the secret of the action is not seen by you are: Take out the array of the YA container of the iterator, From inside next, give the value I for the For loop body disposition, for the value print.
Now the problem is that the data can be used to stack the containers, can the code do?
2. Constructor
How to turn a function into a constructor? There is yield in the body of the function!
The code is as follows:
Def gen ():
print ' Enter '
Yield 1
print ' Next '
Yield 2
print ' Next again '
For I in Gen ():
Print I
You! Python sees yield in the Gen function, knows it can use next, the question is how to play next on the code this container?
When you get the iterator from the container, it is nothing, at the entrance of the container, for the array is the subscript-1 place, for the function is the function entrance is not dry, but everything is ready to owe next.
Start for I in G,next let Itreator crawl to the place where the yield statement exists and return the value,
Again next, crawl to where the next yield statement exists and return the value, in turn until the function returns (at the end of the container).
You must see that the output of the above code is:
Enter
1
Next
2
Next again
3. Use yield
Yield's code-folding ability not only interrupts function execution but also writes down the data at the breakpoint, and next time next book gets back,
This is exactly what the recursive function requires.
For example, the middle sequence traverses the binary tree:
(It should be written by David Mertz)
The code is as follows:
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