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 玫瑰礼盒祝福语大全简短