2014/02/13

Python 3.3 Iterators (迭代)

程式碼內的Reverse是由官方提供的反向迭代

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