python 入门第三课 迭代对象Iterable和迭代器Iterator
迭代对象Iterable和迭代器Iterator
__author__ = 'admin'
from collections.abc import Iterator
from collections.abc import Iterable
print(isinstance([],Iterable))
print(isinstance((),Iterable))
print(isinstance({},Iterable))
print(isinstance('hello',Iterable)) #Iterable
b = isinstance((x for x in range(5)),Iterator) #Iterator could be caught by __next__()
print(b)
print(isinstance(iter('hello'),Iterator)) # # iter(Itreable) into Iterator
# 首先获得Iterator对象:
it = iter([1, 2, 3, 4, 5])
# 循环:
while True:
try:
# 获得下一个值:
x = next(it)
print(x)
except StopIteration:
# 遇到StopIteration就退出循环
break