python之迭代器和生成器
Posted 有猿人
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python之迭代器和生成器相关的知识,希望对你有一定的参考价值。
代码:
1 # x=‘hello‘ 2 # # print(dir(x)) 3 # iter_test=x.__iter__() 4 # 5 # # print(iter_test) 6 # print(iter_test.__next__()) 7 # print(iter_test.__next__()) 8 # print(iter_test.__next__()) 9 # print(iter_test.__next__()) 10 # print(iter_test.__next__()) 11 12 # 13 l=[1,2,3] 14 # for i in l: #i_l=l.__iter_() i_l.__next__() 15 # print(i) 16 17 # index=0 18 # while index < len(l): 19 # print(l[index]) 20 # index+=1 21 22 23 # iter_l=l.__iter__() #遵循迭代器协议,生成可迭代对象 24 # print(iter_l.__next__()) 25 # print(iter_l.__next__()) 26 # 27 # for i in l: 28 # print(i) 29 30 # s={1,2,3} 31 # 32 # # for i in s: 33 # # print(i) 34 # iter_s=s.__iter__() 35 # print(iter_s) 36 # print(iter_s.__next__()) 37 # print(iter_s.__next__()) 38 # print(iter_s.__next__()) 39 # print(iter_s.__next__()) 40 41 # dic={‘a‘:1,‘b‘:2} 42 # iter_d=dic.__iter__() 43 # print(iter_d.__next__()) 44 45 # f=open(‘test11.py‘,‘r+‘) 46 # # for i in f: 47 # iter_f=f.__iter__() 48 # print(iter_f) 49 # # print(iter_f.__next__(),end=‘‘) 50 # print(iter_f.__next__(),end=‘‘) 51 # l=[1,2,3,4,5] 52 # diedai_l=l.__iter__() 53 # while True: 54 # try: 55 # print(diedai_l.__next__()) 56 # except StopIteration: 57 # # print(‘迭代完毕了,循环终止了‘) 58 # break 59 60 # l=[‘die‘,‘erzi‘,‘sunzi‘,‘chongsunzi‘] 61 # 62 # iter_l=l.__iter__() 63 # print(iter_l) 64 # print(iter_l.__next__()) 65 # print(iter_l.__next__()) 66 # print(iter_l.__next__()) 67 # print(iter_l.__next__()) 68 # print(next(iter_l)) #next()---->iter_l.__next__() 69 70 71 72 73 74 75 76 77 78 79 # def test(): 80 # yield 1 81 # yield 2 82 # yield 3 83 # g=test() 84 # print(‘来自函数‘,g) 85 # print(g.__next__()) 86 # print(g.__next__()) 87 88 #三元表达式 89 # name=‘alex‘ 90 # name=‘linhaifeng‘ 91 # res=‘SB‘ if name == ‘alex‘ else ‘帅哥‘ 92 # print(res) 93 94 95 #列表解析 96 # egg_list=[] 97 # for i in range(10): 98 # egg_list.append(‘鸡蛋%s‘ %i) 99 # print(egg_list) 100 101 # l=[‘鸡蛋%s‘ %i for i in range(10)] 102 # l1=[‘鸡蛋%s‘ %i for i in range(10) if i > 5 ] 103 # ll = [‘鸡蛋的%s‘ %i for i in range(10)] 104 # lll = [‘鸡蛋%s‘%i for i in range(10) if i<5] 105 # # l1=[‘鸡蛋%s‘ %i for i in range(10) if i > 5 else i] #没有四元表达式 106 # l2=[‘鸡蛋%s‘ %i for i in range(10) if i < 5] #没有四元表达式 107 # 108 # # print(l) 109 # print(l1) 110 # print(l2) 111 112 # laomuji=(‘鸡蛋%s‘ %i for i in range(10)) #生成器表达式 113 # laomuji = (‘狗蛋%s‘ %i for i in range(10)) 114 # print(laomuji) 115 # 116 # print(laomuji.__next__()) 117 # print(laomuji.__next__()) 118 # print(next(laomuji)) 119 # print(next(laomuji)) 120 # print(next(laomuji)) 121 # print(next(laomuji)) 122 # print(next(laomuji)) 123 # print(next(laomuji)) 124 # print(next(laomuji)) 125 # print(next(laomuji)) 126 127 # l=[1,2,3,34] 128 # map(func,l) 129 130 # print(sum(l)) 131 # print(sum()) 132 # print(sum(i for i in range(10000))) 133 print(sum(i for i in range(101)))
以上是关于python之迭代器和生成器的主要内容,如果未能解决你的问题,请参考以下文章