什么是迭代器?
满足两个条件:1. 有iter()方法,2.有next()方法, 这两个条件叫做迭代器协议.
可迭代对象有:list,tuple,string,dictionary 。。。。
>>> s = [1,2,3,4]
>>> a = iter(s)
>>> next(a)
1
>>> next(a)
2
>>> next(a)
3
>>> next(a)
4
>>> next(a)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
StopIteration
>>> a= {'name':'Li Lie','age': 21,'class':12}
>>> d = iter(a)
>>> next(d)
'name'
>>> next(d)
'age'
>>> next(d)
'class'
>>> next(d)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
StopIteration
for 循环遍历迭代器:
1.调用iter方法返回一个迭代器对象
2.不断调用迭代器对象的next方法得到值
3.处理异常StopIteration