可迭代对象Iterable:

可以直接作用于for循环的对象

1、集合数据类型:list,tuple,dict,set,str

2、generator:包括生成器和带yield的生成器函数

迭代器Iterator:

可以被next()函数调用,并不断返回下一个值的对象

表示一个数据流,甚至是无穷大的数据流,如全体自然数

惰性计算

from collections import Iterable
from collections import Iterator

# 可迭代对象
print(isinstance([1,2,3],Iterable)) # True
print(isinstance((1,2,3),Iterable)) # True
print(isinstance({"one": 1,"two": 2,"three": 3},Iterable)) # True
print(isinstance({1,2,3},Iterable)) # True
print(isinstance("abc",Iterable)) # True
print(isinstance((x for x in range(10)),Iterable)) # True
print(isinstance(100,Iterable)) # False

# 迭代器
print(isinstance((1,2,3),Iterator)) # False
print(isinstance({"one": 1,"two": 2,"three": 3},Iterator)) # False
print(isinstance({1,2,3},Iterator)) # False
print(isinstance("abc",Iterator)) # False
print(isinstance((x for x in range(10)),Iterator)) # True
print(isinstance(100,Iterator)) # False

# 可迭代对象 --> 迭代器
print(isinstance(iter([1,2,3]),Iterable)) # True
print(isinstance(iter((1,2,3)),Iterator)) # True
print(isinstance(iter({"one": 1,"two": 2,"three": 3}),Iterator)) # True
print(isinstance(iter({1,2,3}),Iterator)) # True
print(isinstance(iter("abc"),Iterator)) # True

# 例如
lst = [1, 2, 3, 4, 5, 6]
it = iter(lst) # 转为Iterator

while True:
try:
print(next(it)) # 通过next方法逐个调用
except StopIteration as e:
break

"""OUT:
1
2
3
4
5
6
"""