字符串,列表,元组,字典,集合,生成器这些能通过for循环来遍历的数据类型都是可迭代对象
可通过isinstance判断是不是可迭代对象
>>> from collections import Iterable >>> isinstance('Python', Iterable) True >>> isinstance([1,2,3], Iterable) True >>> isinstance((1,2,3), Iterable) True >>> isinstance({'name':'John','age':22}, Iterable) True >>> isinstance({1,2,3}, Iterable) True >>> isinstance((i*2 for i in range(10)), Iterable) True >>> isinstance(100, Iterable) False
isinstance也可以判断是不是迭代器
>>> from collections import Iterator >>> isinstance('Python', Iterator) False >>> isinstance([1,2,3], Iterator) False >>> isinstance((1,2,3), Iterator) False >>> isinstance({'name':'John','age':22}, Iterator) False >>> isinstance({1,2,3}, Iterator) False >>> isinstance((i*2 for i in range(10)), Iterator) True >>> isinstance(100, Iterator) False
可见可迭代对象不一定是迭代器,但迭代器是可迭代对象
如果要把可迭代对象变为迭代器,可以使用iter()方法
>>> from collections import Iterator >>> isinstance(iter('Python'), Iterator) True >>> isinstance(iter([1,2,3]), Iterator) True >>> isinstance(iter((1,2,3)), Iterator) True >>> isinstance(iter({'name':'John','age':22}), Iterator) True >>> isinstance(iter({1,2,3}), Iterator) True
迭代器可以用next()方法取数据,跟生成器一样