A, generator
1. Definitions (generator): while circulating mechanism while the next element calculation / algorithm
2. The full three conditions
(1) Each call can produce the next element required for loop
(2) If you reach the final after a possible burst StopIteration exception
(3) can be invoked next function
3. How to generate a generator
(1) directly
= L [X * X for X in Range (. 5)] # in parentheses is the list generator G = (X * X for X in Range (. 5)) # in parentheses is the generator Print (type (L)) Print (type (G)) # type function is the return type of the variable in brackets
(2) If the function is included in yield, then the called function generator
(3) next call functions, meet yield return value back
Note: The difference between it and return that, after the return statement, he concluded, but after yield, this function can continue to run
DEF odd (): Print ( " the Step 1 " ) yield 1 # in the odd function, yield responsible for returning, do not return because Print ( " the Step 2 " ) yield 2 Print ( " the Step 3 " ) yield 3 IF __name__ == " __main__ " : One = the Next (the ODD ()) # the ODD () is invoked generator Print (One) TWO = the Next (the ODD ()) Print (TWO) Three = next(odd()) print(three)
He explained: odd here () generator to generate three times, so do not get the results we want, slightly modified, so that the generator generates only once
if __name__ == "__main__": m= odd() one=next(m)#odd()是调用生成器 print(one) two = next(m) print(two) three = next(m) print(three)
(4) for calling the cycle generator
def fib(max): n,a,b = 0,0,1 while n < max: yield b a,b = b,a+b n += 1 if __name__ == "__main__": m2 = fib(10) # print(m2) for i in range(6): rst = next(m2) print(rst)
Second, the source d27_2_iterator_and_yielf_usage.py
https://github.com/ruigege66/Python_learning/blob/master/d27_2_iterator_and_yielf_usage.py
2.CSDN: https: //blog.csdn.net/weixin_44630050 (Xi Jun Jun Moods do not know - Rui)
3. Park blog: https: //www.cnblogs.com/ruigege0000/
4. Welcomes the focus on micro-channel public number: Fourier transform public personal number, only for learning exchanges, backstage reply "gifts" to get big data learning materials