What is a generator
Can be understood as data types, the iterator protocol is implemented automatically (other data types need to call their own built-in __iter__ method, so the generator is an iterative object
Generator classification and performance in Python:
1. Generator function: General function definition, return result with yield statement instead of return statement, yield statement returns one result at a time
def Test (): yield 1 yield 2 # replaces return position = Test ()print(g) Print(G.__next__)print(G.__next__)
2. Generator expression: Similar to list pushed to, but generator returns results on demand
# Three -dimensional expression ' Lyg ' 'SB'if name = ='lyg'else ' Noob ' Print (RES)
# list parsing Egg_list = [] for i in range (10 ' egg%s " % i) print (egg_list)
L = [' egg%s '%i for I in Range]
# l = [i-I in range ' if i>5] #没有四元 no else
print (l)
# with List resolution L = (' egg%s' for in range) # The outside of the generator is expressed in parentheses instead of the []# l Generator expression form print(l)print(Next ( L) # Next essentially calls __next__print(L.__next__())
Summarize:
1: List-resolved [] replaced by () is the claim that its expression
2: List parsing and builder expressions are all traversal programming, except that generator expressions are more memory-efficient
3:python not only uses the iterator protocol, but makes the for loop more generic. Most built-in functions also use iterator protocols to access objects
for In range (4))# instead of for in range (4)])
Generator summary
- Syntax is similar to a function
- Status hangs do not wait for the list to be all generated, production one can yield a
- Auto-Return iterator protocol
Yield two features:
- Equivalent to return to do the returned value
- Preserve the running state of a function
Python builder, List parsing and dictionary parsing