Python3.x基础学习-迭代器用法
迭代器
拥有__iter__方法和__next__方法的对象就是迭代器
1.迭代 迭代是访问集合元素的一种方式,可以将某个数据集内的数据“一个挨着一个的取出来”,就叫做迭代
2.可迭代协议 协议就是互相规定好。可迭代协议的定义非常简单,就是内部实现了__iter__方法。
3.迭代器协议:必须拥有__iter__方法和__next__方法。
for i in 'abc': print(i) for i in [1,2,3]: print(i) for i in (1,2,3): print(i) for i in {'a':1,'b':3}: print(i) # for i in 123: # print(i)
from collections import Iterable print(isinstance('abc',Iterable)) print(isinstance(123,Iterable)) print(isinstance([1,3,4],Iterable)) print(isinstance({1,3,4},Iterable)) print(isinstance({'a':123,'b':321},Iterable)) # True # False # True # True # True
#自定义一个能容纳数据的类,测试可迭代性 from collections import Iterable class Students: def __init__(self): self.names = [] def add(self,name): self.names.append(name) def __iter__(self): #只要内部有__iter__方法,就是可迭代对象 pass stu = Students() stu.add('johnson') print(isinstance(stu,Iterable)) # True
class Students: def __init__(self): self.names = [] self.index = 0 def add(self,name): self.names.append(name) def __iter__(self): return self def __next__(self): if self.index < len(self.names): name = self.names[self.index] self.index+=1 return name else: raise StopIteration stu = Students() #实例化对象 stu.add('johnson') stu.add('may') for i in stu: print(i) # johnson # may iter1 = iter(stu) print(next(iter1)) #StopIteration
#使用迭代器实现斐波那契 0,1,1,2,3,5 class Fib: def __init__(self,n): self.n = n self.index=0 self.a=0 self.b =1 def __iter__(self): return self def __next__(self): if self.index<=self.n: self.a,self.b = self.b,self.b+self.a self.index+=1 return self.a else: raise StopIteration fib = Fib(10) iter2 = iter(fib) print(next(iter2)) print(next(iter2)) print(next(iter2)) print(next(iter2)) # 1 # 1 # 2 # 3