迭代器与迭代对象
作者:互联网
可迭代对象与迭代器
可迭代协议:可迭代对象必须包含__iter__方法,并且返回一个的迭代器。
满足可迭代协议的对象称为可迭代对象。可迭代对象即可使用for …… in的对象。
迭代协议:满足迭代协议的对象时迭代器。
- 包含__iter__方法,并且该方法返回迭代器本身
- 包含__next__方法,调用该方法返回下一个值,当没有值可返回时,抛出StopIteration异常终止迭代。
from collections.abc import Iterable, Iterator
class Iter_obj:
def __init__(self, n) -> None:
self.n = n
self.data = [i for i in range(n)]
def __iter__(self):
"""返回一个迭代器"""
return iter(self.data) # list时可迭代对象但不是可迭代器,
# 基本数据类型的容器类型都是可迭代对象,但都不是迭代器
class Iterator_:
def __init__(self, n):
self.n = n
self.start = 0
def __iter__(self):
"""返回一个迭代器"""
return self # 实现了__iter__和__next__方法的对象就是迭代器,所以返回本身
def __next__(self):
if self.n>self.start:
self.start+=1
return self.start
else:
raise StopIteration()
if __name__ == "__main__":
iter_obj = Iter_obj(3)
print(isinstance(iter_obj, Iterable))
for x in iter_obj: # 可迭代对象可以使用for in语句
print(x)
iterator_ = Iterator_(5)
print(isinstance(iterator_, Iterator))
for x in Iterator_(5):
print(x)
iter方法和next方法
iter方法调用对象的__iter__方法返回一个迭代器。
next方法调用对象的__next__方法返回下一条数据
list、tuple、set、dict都可以使用iter方法得到对应的迭代器,然后可以使用next方法获取下一条数据。
from collections.abc import Iterator, Iterable
def iterable_to_iterator(obj):
print('-'*20)
s = type(obj)
print("%s is Iterable: %s"%(s, isinstance(obj, Iterable)))
print("%s is Iterator: %s"%(s, isinstance(obj, Iterator)))
try:
iterator = iter(obj)
print("%s is Iterator: %s"%(iterator, isinstance(iterator, Iterator)))
while True:
print(next(iterator))
except StopIteration as e:
pass
finally:
print('-'*20)
if __name__ == "__main__":
string = "python"
mylist = ['a', 'b', 'c']
myset = set([1,2,3])
mydict = dict(zip(myset, mylist))
for obj in [string, mylist, myset, mydict]:
iterable_to_iterator(obj)
常见可迭代器与可迭代对象
from collections.abc import Iterator, Iterable
def iterable_or_iterator(obj):
s = type(obj)
print("%s is Iterable: %s"%(s, isinstance(obj, Iterable)))
print("%s is Iterator: %s\n"%(s, isinstance(obj, Iterator)))
if __name__ == "__main__":
zip_ = zip([1,2],[3,4])
dic = dict(zip_)
map_ = map(int, ['1','2'])
enumerate_ = enumerate(['a','b','c'])
for obj in [list(), tuple(), set(), dict(), str(), range(3), zip_,map_, enumerate_,
dic.keys(), dic.values(), dic.items()]:
iterable_or_iterator(obj)
# <class 'list'> is Iterable: True
# <class 'list'> is Iterator: False
# <class 'tuple'> is Iterable: True
# <class 'tuple'> is Iterator: False
# <class 'set'> is Iterable: True
# <class 'set'> is Iterator: False
# <class 'dict'> is Iterable: True
# <class 'dict'> is Iterator: False
# <class 'str'> is Iterable: True
# <class 'str'> is Iterator: False
# <class 'range'> is Iterable: True
# <class 'range'> is Iterator: False
# <class 'zip'> is Iterable: True
# <class 'zip'> is Iterator: True
# <class 'map'> is Iterable: True
# <class 'map'> is Iterator: True
# <class 'enumerate'> is Iterable: True
# <class 'enumerate'> is Iterator: True
# <class 'dict_keys'> is Iterable: True
# <class 'dict_keys'> is Iterator: False
# <class 'dict_values'> is Iterable: True
# <class 'dict_values'> is Iterator: False
# <class 'dict_items'> is Iterable: True
# <class 'dict_items'> is Iterator: False
zip、map、enumerate的返回值是迭代器,dict的keys、values、items的返回值和range的返回值都是可迭代对象,基本数据类型的list、tuple、set、dict、string都是可迭代对象
标签:__,obj,迭代,Iterator,对象,True,Iterable 来源: https://www.cnblogs.com/baiyutang7/p/16407102.html