每天CookBook之Python-061

  • 使用迭代器反转
a = [1, 2, 3, 4]

for x in reversed(a):
    print(x)


class Countdown:
    def __init__(self, start):
        self.start = start

    def __iter__(self):
        n = self.start
        while n > 0:
            yield n
            n -= 1

    def __reversed__(self):
        n = 1
        while n <= self.start:
            yield n
            n += 1


for i in reversed(Countdown(5)):
    print(i)

for i in Countdown(5):
    print(i)

out

4
3
2
1
1
2
3
4
5
5
4
3
2
1
posted @ 2016-07-22 20:10  4Thing  阅读(85)  评论(0编辑  收藏  举报