Python for循环的本质——迭代器 可迭代的对象

limalove / 2023-05-17 / 原文

 

Python的for循环本质上就是通过不断调用next()函数实现的,例如:

for x in [1, 2, 3, 4, 5]:
    pass

实际上等价于:

# 首先获得Iterator对象:
it = iter([1, 2, 3, 4, 5])
# 循环:
while True:
    try:
        # 获得下一个值:
        x = next(it)
    except StopIteration:
        # 遇到StopIteration就退出循环
        break

 

 

 

 

 

 

迭代器模式可用来:

1,为遍历不同的聚合结构提供一个统一的接口。