首页 > 其他 > 详细

迭代器

时间:2017-06-23 20:07:30      阅读:227      评论:0      收藏:0      [点我收藏+]

可迭代对象Iterable

以直接作用于 for 循环的数据类型有以下几种:

一类是集合数据类型,如 list 、 tuple 、 dict 、 set 、 str 等;

一类是 generator ,包括生成器和带 yield 的generator function。

这些可以直接作用于 for 循环的对象统称为可迭代对象: Iterable 。

 

迭代器

判断是否可迭代isinstance

from collections import Iterator
b=isinstance((x for x in range(1,100)),Iterator)

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

 

生成器都是 Iterator 对象,但 list 、 dict 、 str 虽然是 Iterable ,却不是 Iterator 。

把 list 、 dict 、 str 等 Iterable 变成 Iterator 可以使用 iter() 函数:

from collections import Iterator
b=isinstance(iter(abc),Iterator) #TRUE

总结

  • 凡是可作用于 for 循环的对象都是 Iterable 类型;
  • 凡是可作用于 next() 函数的对象都是 Iterator 类型
  • 集合数据类型如 list 、 dict 、 str 等是 Iterable 但不是 Iterator ,不过可以通过 iter() 函数获得一个 Iterator 对象。

迭代器

原文:http://www.cnblogs.com/arthas-zht/p/7071320.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!