As you may have heard, functions with yield are called generator (generators) in Python, what is generator?
Let's throw away the generator and show the concept of yield with a common programming topic.
How to generate Fibonacci numbers
Fibonacci (Fibonacci) is a very simple recursive sequence in which any number can be added together with the first two numbers, except for the number one and the second. It is a very simple question to output the first N number of Fibonacci columns with a computer program, and many beginners can easily write the following functions:
Listing 1. Simple output Fibonacci Number column N
Def FAB (max):
N, a, b = 0, 0, 1 while
n < max:
print B
A, B = B, a + b
n = n + 1
Executive Fab (5), we can get the following output:
>>> Fab (5)
1
1
2
3
5
The results are fine, but experienced developers will point out that printing numbers directly in the FAB function can cause the function to be less reusable because the FAB function returns None, and other functions cannot get the sequence that the function generates.
To improve the reusability of the Fab function, it is best not to print the columns directly, but to return to a List. The following is the second version of the FAB function rewrite:
Listing 2. Output Fibonacci Number List N Second Edition
Def FAB (max):
N, a, b = 0, 0, 1
L = [] while
n < max:
l.append (b)
A, B = B, a + b
n = n + 1 return
L
You can print out the List returned by the FAB function by using the following methods:
>>> for N in Fab (5):
... Print n
...
1
1
2
3
5
The rewritten fab function satisfies the need for reusability by returning a list, but more experienced developers will note that the memory consumed by the function increases as the parameter max increases, and if you want to control the memory footprint, it is best not to use the list
To save the intermediate results instead of iterating through the Iterable object. For example, in python2.x, the code:
Listing 3. Iterate through the Iterable object
For I in range (1000): Pass
Causes a List of 1000 elements to be generated, and the code:
For I in xrange (1000): Pass
A List of 1000 elements is not generated, but the next value is returned in each iteration, with little memory space. Because Xrange does not return the List, it returns a Iterable object.