1、迭代器
1.1、迭代器创建:指定数据创建迭代器(使用iter()和next() )
x = [1, 2, 3] #定义一个列表:<class 'list'> y = iter(x) #创建一个可迭代对象:<class 'list_iterator'> #print(next(y)) # 1 #print(next(y)) # 2 #print(next(y)) # 3 #print(next(y)) # 迭代结束会后返回异常StopIteration错误 for i in y: print(i,end=" ") print() # 1 2 3
1.2、迭代对象:定义魔术方法:__next__()
和__iter__()
class A: def __init__(self): self.x=0 def __next__(self): self.x += 1 if self.x>10: raise StopIteration return self.x def __iter__(self): return self a = A() print(list(a)) #for i in a: # print(i) # [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]