to python3 (eleven) Generator

# Long as a list of the formula [] into () 
L = [X * X for X in Range (10 )]
 Print (L)   # [0,. 1,. 4,. 9, 16, 25, 36, 49, 64, 81] 
G = (X * X for X in Range (10 ))
 Print (G)   # <Generator Object <genexpr> AT 0x00000000021789C8> 
# Print (Next (G)) # 0 
# Print (Next (G)) . 1 # 
# Print (next (g)). 4 # 
# Print (next (g)). 9 # 
# Generator algorithm is stored, next (g), to calculate a value of the element g of each call, 
# until when calculating the last element, no more elements, throw StopIteration mistakes. 
# Generator also be iterative
for n- in G:
     Print (n-) 


# 0 
# . 1 
# . 4 
# . 9 
# 16 
# 25 
# 36 
# 49 
# 64 
# 81 
# After creating a generator, substantially never called next (), but by for loop to iterate it, and do not care about StopIteration errors. 
DEF FIB (max): 
    n-, A, B = 0, 0,. 1
     the while n-< max:
         Print (B) 
        A, B = B, A + B 
        n- =. 1 + n-
     return  ' DONE' 


FIB ( . 8 ) 


# If a function included in the definition yield keyword, then this function is no longer a common function, but a Generator 
DEF FIB (max): 
    n-, A, B = 0, 0,. 1
     the while n- < max:
         the yield B 
        A, B = B, A + B 
        n- =. 1 + n-
     return  ' DONE ' 


# -------------------------- ------------------------------------------- 
#   execution flow generator and function Different. Function is the execution order, encountered a return statement or statement returns the last line of the function. Becomes a function generator, each time next call () is executed, encounters yield return statement, the statement of the yield from the last execution again returned to continue. 
# ------------------------------------------------- --------------------
DEF ODD ():
     Print ( ' STEP. 1 ' )
     yield . 1
     Print ( ' STEP 2 ' )
     yield (. 3 )
     Print ( ' STEP. 3 ' )
     yield (. 5 ) 


# ODD Generator is, during execution, it encounters yield interrupted, the next time to continue. After performing three times yield, has no yield can be executed, so the 4th call next (o) on the error. 
# However, when used for the cycle call generator, the generator was found not get the return value of the return statement. If you want to get the return value must be captured StopIteration error in the return value contains the value of StopIteration: 
G = FIB (. 5 )
 the while . 1 :
     the try  :
        X= next(g)
        print('g:', x)
    except StopIteration as e:
        print('Generator return value:', e.value)
        break

 

Guess you like

Origin www.cnblogs.com/shaozhiqi/p/11543570.html