python生成器及yield关键字
简明示例:
1 def y(): 2 for i in 'abc': 3 yield i
演示结果:
>>> x=y() >>> next(x) 'a' >>> next(x) 'b' >>> next(x) 'c' >>> next(x) Traceback (most recent call last): File "<pyshell#6>", line 1, in <module> next(x) StopIteration
斐波那契数:
1 def fibonacciNum(): 2 a,b=0,1 3 while True: 4 a,b=b,a+b 5 yield a
演示结果:
1 >>> f=fibonacciNum() 2 >>> next(f) 3 1 4 >>> next(f) 5 1 6 >>> next(f) 7 2 8 >>> next(f) 9 3 10 >>> next(f) 11 5 12 >>> next(f) 13 8 14 >>> next(f) 15 13 16 >>> next(f) 17 21 18 >>> for i in f: 19 if i>50: 20 break 21 else: 22 print(i) 23 24 25 34 26 >>> for i in fibonacciNum(): 27 if i>50: 28 break 29 else: 30 print(i) 31 32 33 1 34 1 35 2 36 3 37 5 38 8 39 13 40 21 41 34
自动生成可迭代序列:
1 >>> a=[i for i in range(10)] #自动生成列表 2 >>> a 3 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] 4 >>> a=[i for i in range(10) if i%2] 5 >>> a 6 [1, 3, 5, 7, 9] 7 >>> b={i:i+1 for i in range(10) if i%2} #自动生成字典 8 >>> b 9 {1: 2, 3: 4, 5: 6, 7: 8, 9: 10} 10 >>> c={i for i in (1,2,2,3,3,3,4,5,5)} #自动生成集合 11 >>> c 12 {1, 2, 3, 4, 5} 13 >>> s="i for i in 'abc'" #不可以自动生成字符串 14 >>> s 15 "i for i in 'abc'" 16 >>> t=(i for i in range(5)) #不可以自动生成元组 17 >>> t 18 <generator object <genexpr> at 0x0000000003122360> #实际是生成器对象 19 >>> next(t) 20 0 21 >>> next(t) 22 1 23 >>> next(t) 24 2 25 >>> next(t) 26 3 27 >>> next(t) 28 4 29 >>> next(t) 30 Traceback (most recent call last): 31 File "<pyshell#43>", line 1, in <module> 32 next(t) 33 StopIteration 34 >>> for i in t: 35 print(i) 36 37 #已经迭代到末尾,所以无值打印输出 38 >>> t=(i for i in range(5)) 39 >>> for i in t: 40 print(i) 41 42 43 0 44 1 45 2 46 3 47 4 48 >>> sum(t) 49 0 #已经迭代到末尾,所以求和为0 50 >>> t=(i for i in range(5)) 51 >>> sum(t) 52 10