Python迭代器和生成器
'''list = [1,2,3,4] it = iter(list) print(next(it)) print(next(it)) #for x in it: # print(x,end=' ') import sys while True: try: print(next(it)) except StopIteration: sys.exit() ''' # 迭代器,实现__iter__,__next__ class MyNumber: def __iter__(self): self.a = 1 return self def __next__(self): x = self.a self.a +=1 return x myclass = MyNumber() for i in myclass: print(i) if i > 20: break # 生成器,使用 yield 的函数,有yield函数即为生成器 # 每次遇到yield时,函数暂停保存信息 import sys def fibonacci(n): a = 0 b = 1 cnt = 0 while True: if(cnt > n): return yield a a , b = b, a + b cnt+=1 f = fibonacci(10) while True: try: print(next(f), end=" ") except StopIteration: sys.exit()
还有反向迭代器__reversed__,生成器表达式,等等。