Python3 生成器
1 ''' 2 列表生成式 3 ''' 4 5 # a1 = [x for x in range(10)] 6 # a2 = [x*2 for x in range(10)] 7 # print(a1) 8 # print(a2) 9 # 10 # def fun1(x): 11 # return x**3 12 # a3 = [fun1(x) for x in range(10)] 13 # print(a3) 14 # 15 # # 列表生成式 16 # # 取值方式 17 # b = ['asd',8,9,10] 18 # w,x,y,z = b 19 # print(w,x,y,z) 20 # print(b) 21 # 22 # 23 # # 生成器 24 # c = (x*2 for x in range(10)) # c是生成器对象 25 # print(c) # <generator object <genexpr> at 0x00000286BEF21CA8> 26 # # print(next(c)) # 等价于 c.__next__(),在Python2中等价于 c.next() 27 # # print(next(c)) 28 # # print(next(c)) 29 # # print(next(c)) # 超出范围会报错 30 # 31 # # 生成器是可迭代对象 32 # import time 33 # for i in c: # for 对c进行了一个next()的功能 34 # print(i) 35 # # time.sleep(1) 36 37 ''' 38 生成器的两种创建方式 39 1.(x*2 for x in range(10)) 40 2.yield 41 ''' 42 43 # def fun2(): 44 # print('###') # 此打印没有显示 45 # yield 1 46 # print(fun2()) # fun2()是生成器对象 47 # 48 # def fun3(): 49 # print('###') 50 # yield 1 51 # 52 # print('asd') 53 # yield 2 54 # 55 # return None 56 # 57 # c1 = fun3() 58 # # next(c1) # next()被返回1 59 # # next(c1) # next()被返回2 60 # 61 # for i in fun3(): 62 # print(i) # ‘###’, 1, ‘asd', 2 63 # # 此时的1,2是上面的返回值 64 65 66 ''' 67 什么是可迭代对象,可迭代对象拥有iter方法 68 ''' 69 70 # list1 = [1,2,3] 71 # list1.__iter__() 72 # 73 # tup1 = (1,2,3) 74 # tup1.__iter__() 75 # 76 # disc1 = {'asd':123} 77 # disc1.__iter__() 78 79 80 81 # # 斐波那契数列 82 # # 0 1 1 2 3 5 8 13 21 34 83 # def fun4(max): 84 # q,before,after = 0,0,1 85 # while q < max: 86 # print(after) 87 # before,after = after,before+after 88 # q += 1 89 # fun4(10) 90 # print(fun4(8)) 91 92 # # 使用生成器创建斐波那契数列 93 # def fun5(max): 94 # q,before,after = 0,0,1 95 # while q < max: 96 # 97 # yield before 98 # before,after = after,before+after 99 # q = q + 1 100 # z = fun5(8) 101 # print(z) 102 # print(next(z)) 103 # print(next(z)) 104 # print(next(z)) 105 # print(next(z)) 106 # print(next(z)) 107 108 109 ''' 110 send 方法 111 ''' 112 # def fun5(): 113 # print('a1') 114 # a = yield 1 115 # print(a) 116 # 117 # yield 2 118 # x = fun5() 119 # x1 = x.send(None) # 等价于next(x) 120 # # 第一次send前没有next,只能传一个send(None) 121 # h = x.send('aaaaaaaaa') 122 # print(h) 123 124 ''' 125 send 比 next 多一个功能,是可以传入一个参数给其中的变量 126 127 '''