首页 > 文章列表 > python for循环的本质探究

python for循环的本质探究

pythonfor循环
177 2022-08-07

1、遍历可迭代的对象。通过iter()函数获得可迭代对象Iterable的迭代器,然后不断调用next()方法获得下一个值。

并将其赋予item值,当遇到StopIteration异常时,循环结束。

2、遍历迭代器。循环迭代器不断调用next()方法获取下一个值。

并将其赋予item值,在遇到StopIteration异常时,循环结束。

实例

a = list1.__iter__()    #<list_iterator object at 0x0000025C8E1F8A60>
while True:
    try:
        i=next(a)
        print(i)
    except StopIteration as r:
        # print('StopIteration')
        break

本文教程操作环境:windows7系统、Python 3.9.1,DELL G3电脑。