http://anandology.com/python-practice-book/iterators.html html
Problem 1: Write an iterator class reverse_iter
, that takes a list and iterates it from the reverse direction. ::python
>>> 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
spa
ri = reverse_iter([1,2,3,4])
print ri.next()
print ri.next()
print ri.next()
print ri.next()
print ri.next()code