python 入門第三課 迭代對象Iterable和迭代器Iterator

迭代對象Iterable和迭代器Iteratorcode

__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
相關文章
相關標籤/搜索