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 祝福语结婚诗句大全简短