一、可迭代对象:可以直接作用于for循环的对象称为可迭代对象:Iterable
比如:list、tuple、dict、set、str、生成器
可以使用isinstance()来判断:
>>> from collections import Iterable >>> isinstance([],Iterable) True >>> isinstance((),Iterable) True >>> isinstance('abc',Iterable) True >>> isinstance(x for x in range(10),Iterable) SyntaxError: Generator expression must be parenthesized if not sole argument >>> isinstance((x for x in range(10)),Iterable) True >>> isinstance([x for x in range(10),Iterable) SyntaxError: invalid syntax >>> isinstance([x for x in range(10)],Iterable) True >>> isinstance(100,Iterable) False >>> isinstance('',Iterable) True >>> isinstance(0.2,Iterable) False >>> isinstance({},Iterable) True >>>
二、迭代器:不但可以作用于for循环,还可以通过next()函数调用不断返回下一个值的对象称为迭代器:Iterator。
也可以通过isinstance()判断一个对象是否是Iterator对象,可以看到list、dict、tuple、str对象虽然是Iterable,但是不是Iterator:
>>> from collections import Iterator >>> isinstance((x for x in range(10)),Iterator) True >>> isinstance([],Iterator) False >>> isinstance({},Iterator) False >>> isinstance((),Iterator) False >>> >>> isinstance('abcd',Iterator) False >>>
可以通过iter()函数将可迭代对象转换为迭代器,参数必须是可迭代的对象,否则会报错:
>>> isinstance(iter([]),Iterator) True >>> isinstance(iter({}),Iterator) True >>> isinstance(iter(()),Iterator) True >>> isinstance(iter('abc'),Iterator) True >>> isinstance(iter(123),Iterator) Traceback (most recent call last): File "<pyshell#38>", line 1, in <module> isinstance(iter(123),Iterator) TypeError: 'int' object is not iterable >>>