ls = [1,2,3,4,5] it = iter(ls) print(it) try: while True: print(next(it)) except StopIteration as stop: pass class Reverse: """Iterator for looping over a sequence backwards.""" def __init__(self, data): self.data = data self.index = len(data) def __iter__(self): return self def __next__(self): if self.index == 0: raise StopIteration self.index = self.index - 1 return self.data[self.index] r = Reverse(ls) try: while True: print(next(r)) except StopIteration as stop: pass
參考資料:
http://docs.python.org/3/tutorial/classes.html#iterators
http://docs.python.org/3/library/stdtypes.html#iterator-types