列表生成式:
1 [i * 2 for i in range(10)] 2 Out[4]: [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
生成器
生成器不能切片,只有在调用时才会生成相应的数据
为了节省内存,只会记住当前的位置。 通过 .__next__() ,next(f),循环调用
斐波那契数列:
1 def fib(max): 2 n,a,b = 0,0,1 3 while n <m
1 a = ( i*2 for i in range(100000)) 2 3 print(a) 4 5 # ============================================================================= 6 # <generator object <genexpr> at 0x09365960> 7 # =============================================================================
ax: 4 print(b) 5 a,b = b,a+b 6 n += 1 7 fib(10) 8 9 # ============================================================================= 10 # 1 11 # 1 12 # 2 13 # 3 14 # 5 15 # 8 16 # 13 17 # 21 18 # 34 19 # 55 20 # =============================================================================
关于a,b = b, a+b 的解释
相当于 t = (b,a+b)
a = t[0]
b = t[1]
生成器 : 把print(b) 改为 yield b 此时斐波那契数列变成生成器 1 def fib(max):
2 n,a,b = 0,0,1 3 while n <max: 4 yield b 5 a,b = b,a+b 6 n += 1 7 return 'done' 8 fib(10) 9 10 # ============================================================================= 11 # 12 # f = fib(10) 13 # 14 # for i in f: 15 # print(i) 16 # 17 # 1 18 # 1 19 # 2 20 # 3 21 # 5 22 # 8 23 # 13 24 # 21 25 # 34 26 # 55 27 # 28 # f = fib(10) 29 # 30 # f.__next__() 31 # Out[39]: 1 32 # 33 # f.__next__() 34 # Out[40]: 1 35 # 36 # f.__next__() 37 # Out[41]: 2 38 # 39 # f.__next__() 40 # Out[42]: 3 41 # 42 # f.__next__() 43 # Out[43]: 5 44 # 45 # f.__next__() 46 # Out[44]: 8 47 # 48 # f.__next__() 49 # Out[45]: 13 50 # 51 # f.__next__() 52 # Out[46]: 21 53 # 54 # f.__next__() 55 # Out[47]: 34 56 # 57 # f.__next__() 58 # Out[48]: 55 59 # 60 # f.__next__() 61 # Traceback (most recent call last): 62 # 63 # File "<ipython-input-49-39ec527346a9>", line 1, in <module> 64 # f.__next__()
#StopIteration: done 65 # ================================================================
f斐波那契数列的生成器。这里使用循环是return 没有打印。使用next方法最后会报错
return 在这里使用的时候是为了异常的时候报错
1 def fib(max): 2 n,a,b = 0,0,1 3 while n <max: 4 yield b 5 a,b = b,a+b 6 n += 1 7 return 'done' 8 f = fib(10) 9 g = fib(6) 10 while True: 11 try: 12 x = next(g) 13 print('g:',x) 14 15 except StopIteration as e: 16 print("Generator return value:",e.value) 17 break