# This is a learning note for the Liaoche teacher Python tutorial
1 , overview
The list elements are calculated according to an algorithm, and the subsequent elements are continuously deduced during the loop. This side loop is calculated on the side of the mechanism, called the generator: generator
1.1 , creating Generator
1) Method One
As soon as you change the [] form of a list to (), you create a generator
L = [x * x for x in range (Ten)] # This is a list-generated
g = (x * x for x in range ) # this is Generator
>>> g
<generator Object <genexpr> at 0x1022ef630>
Generator value cannot be printed directly, you need to use the Next () function obtained, or by for Loops Print
Each call returns a value of generator, and when all values are returned, the call will be error stopiteration
>>> for N in G:
... print (n)
2) Method Two
In the function body, there is yield. Of course, the function of generator can also get the return value with next () or for loop
The function is executed sequentially, the return statement is encountered, or the last line function statement returns
The generator function, which executes at each call to next (), encounters a yield statement return, executes again from the yield statement that was last returned
Def odd ():
Print (' Step 1 ')
Yield 1
Print (' Step 2 ')
Yield (3)
Print (' Step 3 ')
Yield (5)
>>> o = Odd ()
>>> Next (o) # Next (Odd ()) invokes the same effect. for loop call See example
Step 1
1
>>> Next (O)
Step 2
3
>>> Next (O)
Step 3
5
2 , examples
1 , writing a Fibonacci sequence. Generator function
# function Writing
def fib (max):
N, a, b = 0, 0, 1
While n < max:
Yield b
A, B = B, A + b
n = n + 1
Return ' Done '
# for Loop gets the return value, but does not get the error returned after generator execution
F=FIB (6) # defines a generator object F
For N in F:
print (n)
# get worth while, get generator's error return
G=FIB (6)
While True:
Try
X=next (g)
Print (' G ', X)
Except Stopiteration as e: # catch error
print (' Generator return value: ', E.value) # Enter the wrong return value
Break
2 , writing a Yang Hui triangle. Generator function
#-*-Coding:utf-8-*-
def triangles ():
N=[1]
While True:
Yield N #generator函数与普通函数的差别: During execution, the yield is interrupted and the next execution continues
N.append (0)
N=[N[I-1] + n[i] for I in range (len (N))] #杨辉三角的生成式
if __name__ = = ' __main__ ': # if the. py file is running, execute the following command. For commissioning
N=0
For T in triangles ():
Print (t)
N=n+1
if n = = 10:
Break
Python Learning note __3.4 Chapter Builder