标签:color array done val 循环 中断 bre int 生成
1 #!/usr/bin/env python 2 #created by Baird 3 4 array = (i*2 for i in range(10)) 5 6 print(array.__next__()) #在循环之后调用next方法会报错,输出0 7 print(array.__next__()) #输出2 8 print(array.__next__()) #输出4 9 10 for i in array: #生成器对象无法使用下标调用 11 print(i) #输出6-18 12 13 def fib(max): #创建一个生成器 14 n,a,b=0,0,1 15 while n<max: 16 yield b #中断,接收到 next() 或 send()时恢复中断 17 a,b=b,a+b 18 n=n+1 19 return("done") #用于捕捉异常,判断生成器边界 20 21 f = fib(5) 22 print("\n",f) 23 24 while True: 25 try: 26 a = next(f) 27 except StopIteration as e: #捕捉异常 28 print(e.value) 29 break
标签:color array done val 循环 中断 bre int 生成
原文地址:https://www.cnblogs.com/baird/p/9541395.html