当前位置:Gxlcms > Python > python迭代器的实例详解

python迭代器的实例详解

时间:2021-07-01 10:21:17 帮助过:50人阅读

可直接作用于for循环的对象叫做可迭代对象(iterable);

可被next()函数调用并不断返回下一个值的对象称为迭代器(iterator);

所有的可迭代对象均可以通过内置函数iter()来转变为迭代器。

在使用for循环的时候,程序就会自动调用即将处理的对象的迭代器对象,然后使用它的next()方法,直到检测一个stoplteration异常。

  1. >>> l = [4,5,6,7,8,9,0] #这是一个列表
  2. >>> i = iter(l) #可迭代对象转换为迭代器;
  3. >>> next(i)
  4. 4
  5. >>> next(i)
  6. 5
  7. >>> next(i)
  8. 6
  9. >>> next(i)
  10. 7
  11. >>> next(i)
  12. 8
  13. >>> next(i)
  14. 9
  15. >>> next(i)
  16. 0
  17. >>> next(i)
  18. Traceback (most recent call last):
  19. File "<stdin>", line 1, in <module>
  20. StopIteration

因为列表中么有超过0的数字,所以当范围超过的话,就会返回一个StopIteration异常。

在生产环境中如何判断呢

  1. >>> L = [4,5,6]
  2. >>> I = L.__iter__()
  3. >>> L.__next__()
  4. Traceback (most recent call last):
  5. File "<stdin>", line 1, in <module>
  6. AttributeError: 'list' object has no attribute '__next__'
  7. >>> I.__next__()
  8. 4
  9. >>> from collections import Iterator, Iterable
  10. >>> isinstance(L, Iterable)
  11. True
  12. >>> isinstance(L, Iterator)
  13. False
  14. >>> isinstance(I, Iterable)
  15. True
  16. >>> isinstance(I, Iterator)
  17. True
  18. >>> [x**2 for x in I]
  19. [25, 36]

以上就是python迭代器的实例详解的详细内容,更多请关注Gxl网其它相关文章!

人气教程排行