1. 程式人生 > >Python3 生成器

Python3 生成器

超出範圍 span 斐波那契數 ext ## 創建方式 取值 log tor

  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 ‘‘‘

Python3 生成器