每天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
 
                    
                     
                    
                 
                    
                
 
                
            
         
         浙公网安备 33010602011771号
浙公网安备 33010602011771号