迭代器是一种对象
迭代器vs可迭代对象
列表、元组、字典和集合都是可迭代的对象。所有这些对象都有用于获取迭代器的 iter() 方法
mylist = [1,2,3,4,5,6,7,8]
myit = iter(mylist)
print(next(myit))
print(next(myit))
print(next(myit))
print(next(myit))
print(next(myit))
for遍历迭代器
创建迭代器
- 要把对象/类创建为迭代器,必须为对象实现 iter() 和 next() 方法。
stoplteration
class num_2:
def __iter__(self):
self.a=1
return self
def __next__(self):
if(self.a <= 20):
x = self.a
self.a += 3
return x
else:
raise StopIteration
my = num_2()
myiter=iter(my)
for i in myiter:
print(i)
标签:__,迭代,myit,self,next,基础教程,print
From: https://www.cnblogs.com/braveman1021/p/16998576.html