目录
可迭代对象
(1)list:列表
例如:
运行结果:
(2)set:元组
例如:
运行结果:
(3)tuple:集合
例如:
运行结果:
(4)dict:字典
例如:
运行结果:
(5)str:字符串
例如:
运行结果:
(6)generator:生成器
例如:
运行结果:
Ps:生成器是典型的迭代器。
迭代器
定义
能够被 next 调用,并且返回下一个值的叫做迭代器。
collections模块
系统内置模块,用于判断变量
用法
#可以使用全局函数中的 isinstance( ) 做判断
from collections import Iterator
from collections import Iterable
x = …
print(isinstance(x,Iterator))
print(isinstance(x,Iterable))
Iterator用于判断该变量是不是迭代器对象
Iterable用于判断该变量是不是可迭代对象
Ps:
(1)迭代器对象是可迭代对象,可迭代对象不一定是迭代器。
(2)全局函数中的 iter( ) 可将一个迭代对象转换为迭代器。
总结
1.凡是可作用于 for 循环的对象都是 Iterable 类型;
2.凡是可作用于 next( ) 函数的对象都是 Iterator 类型;
3.集合数据类型如 list、tuple、set、dict 等是 Iterable 对象而不是 Iterator 对象;
4.Iterator 对象一定是 Iterable 对象,而 Iterable 对象不一定是 Iterator 对象;
5.可以通过全局函数中的 iter( ) 将 Iterable 对象转换为 Iterator 对象,目的是减少占用的内存。