http://anandology.com/python-practice-book/iterators.html
Problem 1: Write an iterator class reverse_iter, that takes a list and iterates it from the reverse direction. ::
>>> it = reverse_iter([1, 2, 3, 4]) >>> it.next() 4 >>> it.next() 3 >>> it.next() 2 >>> it.next() 1 >>> it.next() Traceback (most recent call last): File "<stdin>", line 1, in <module> StopIteration写了一个,倒是实现了,不知道是不是全世界效率最低的。class reverse_iter: """docstring for ClassName""" def __init__(self,target): self.current = 0 self.target = target self.len = len(target) print self.len def next(self): if self.current < self.len: self.current+=1 return self.target[self.len-self.current] else: raise StopIteration() def __iter__(self): return self
ri = reverse_iter([1,2,3,4])print ri.next()print ri.next()print ri.next()print ri.next()print ri.next()
转载于:https://www.cnblogs.com/jin-wen-xin/p/7731815.html
