反向迭代
常规方法
将可迭代对象列表化,用列表的reversed方法反向输出。
这种方法的弊端就是在建立列表的过程中占用大量的内存空间。
# Print a file backwards
f = open('somefile')
for line in reversed(list(f)):
print(line, end='')
高阶方法:反向迭代器
在类中定义__reversed__()方法,使其具有反向迭代的能力
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
rCountdown = Countdown(10)
print("normal countdown")
for item in rCountdown:
print(item)
print("reversed countdown == countup")
for item in reversed(rCountdown):
print(item)
输出结果
normal countdown
10
9
8
7
6
5
4
3
2
1
reversed countdown == countup
1
2
3
4
5
6
7
8
9
10
Process finished with exit code 0