zl程序教程

您现在的位置是:首页 >  后端

当前栏目

Python for循环内部实现的一个sample

Python循环 实现 一个 for 内部 Sample
2023-09-11 14:17:56 时间
#!/usr/bin/env python
# -*- coding: utf-8 -*-
it = iter([1,2,3,4,5])
while True:
    try:
        x = next(it)
        print(x)
    except StopIteration as e:
        print('catch StopIteration')
        break

因为Python的Iterator对象表示的是一个数据流,Iterator对象可以被next()函数调用并不断返回下一个数据,直到没有数据时抛出StopIteration错误。可以把这个数据流看做是一个有序序列,但我们却不能提前知道序列的长度,只能不断通过next()函数实现按需计算下一个数据,所以Iterator的计算是惰性的,只有在需要返回下一个数据时它才会计算。