Python笔记(十六):迭代器

时间:2023-03-09 17:29:54
Python笔记(十六):迭代器

(一)iterable对象和Iterator对象的区别

iterable对象(可迭代的对象):可以使用for循环,例如:字符串、列表 、字典 、集合等

Iterator对象(迭代器):除了可以用for循环外,还可以用next()不断获取下一个元素.

__iter__() 和__next__()这2个方法都实现了的,就是Iterator。只实现__iter__() 方法的就是iterable。

 from collections import Iterable
from collections import Iterator class peo(): def __init__(self,x):
self.x = x
def __iter__(self):
return self p = peo([1,2,3,4]) print(isinstance(p,Iterable)) #判断是否是Iterable对象
 print(isinstance(p,Iterator))

Python笔记(十六):迭代器

__iter__() 和__next__()2个方法都实现的,才是迭代器:Iterator

 from collections import Iterable
from collections import Iterator class peo(): def __init__(self,x):
self.x = x
def __iter__(self):
return self
def __next__(self):
return self p = peo([1,2,3,4]) print(isinstance(p,Iterable))
print(isinstance(p,Iterator))

Python笔记(十六):迭代器

所以,Iterator对象肯定也是iterable对象,但iterable对象却不一定是Iterator对象。

我们可以使用next()不断获取Iterator对象的下一个元素,直到抛出StopIteration错误

 the_iter = iter([1,2,3])

 print(next(the_iter))
print(next(the_iter))
print(next(the_iter)) print(next(the_iter))

Python笔记(十六):迭代器

(二)for循环的工作方式

在上面的例子中,实际可以用for循环.

 the_iter = iter([1,2,3])

 for i in the_iter:
print(i)

for循环的工作方式:上面这段代码实际上和下面这段代码是一样的

 the_iter = iter([1,2,3])

 while True:
try:
element = next(the_iter)
print(element)
except StopIteration:
# 如果抛出异常,退出循环
break