迭代器
字符串召耘、列表百炬、元組、字典污它、集合都是可迭代的剖踊。判斷是否可迭代只需要看對象是否有__iter__
方法庶弃,如果有了__iter__
方法,且同時擁有__next__
方法德澈,就是迭代器了歇攻。
from collections.abc import Iterable
li = [1,2,3,4]
tu = (1,2,3,4)
di = {1:2,3:4}
se = {1,2,3,4}
st = '1234'
print(isinstance(li,Iterable))
print(isinstance(tu,Iterable))
print(isinstance(di,Iterable))
print(isinstance(se,Iterable))
print(isinstance(st,Iterable))
返回結(jié)果:
True
True
True
True
True
查看對象的方法:
# 列表對象
print(dir([]))
'''
['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']
'''
當(dāng)給對象加上__iter__
方法后,其函數(shù)就會發(fā)生改變梆造,可以看到缴守,里面多出來了__next__
方法
l = [1,2,3,4]
print(dir(l.__iter__()))
'''
['__class__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__length_hint__', '__lt__', '__ne__', '__new__', '__next__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setstate__', '__sizeof__', '__str__', '__subclasshook__']
'''
# 我們可以使用__next__方法取值
print(l.__iter__().__next__()) # 1
下面使用__next__
方法取一組值
s = '12345'
l = s.__iter__()
print(l.__next__()) # 1
print(l.__next__()) # 2
print(l.__next__()) # 3
print(l.__next__()) # 4
for 循環(huán)的本質(zhì)
s = '12345'
l = s.__iter__()
while True:
try:
print(l.__next__())
except StopIteration: # StopIteration 迭代器沒有更多的值
break