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 生日广州男生祝福语简短