Python的迭代器和生成器使用实例
一、迭代器Iterators
迭代器仅是一容器对象,它实现了迭代器协议。它有两个基本方法:
1)next方法
返回容器的下一个元素
2)__iter__方法
返回迭代器自身
迭代器可使用内建的iter方法创建,见例子:
>>>i=iter('abc')
>>>i.next()
'a'
>>>i.next()
'b'
>>>i.next()
'c'
>>>i.next()
Traceback(mostrecentcalllast):
File"<string>",line1,in<string>
StopIteration:
classMyIterator(object): def__init__(self,step): self.step=step defnext(self): """Returnsthenextelement.""" ifself.step==0: raiseStopIteration self.step-=1 returnself.step def__iter__(self): """Returnstheiteratoritself.""" returnself forelinMyIterator(4): printel --------------------
热门推荐
10 精简祝福语简短小故事
11 简短新年红包祝福语大全
12 女士简短祝福语大全集
13 周一祝福语简短精辟
14 离职送别文案祝福语简短
15 卖奶茶开张祝福语简短
16 社团迎新祝福语简短英语
17 朋友买新房祝福语简短
18 中考祝福语 简短 签状