使用內置的reversed()函數
>>> a = [1, 2, 3, 4]
>>> for x in reversed(a):
... print(x)out
4
3
2
1
反向迭代僅僅當對象的大小可預先確定或者對象實現了 _reversed_()的特殊方法時才能生效。如果兩者都不符合 ,必須將對象轉換成一個列表才行。
f=open('somefile')
for line in reversed(list(f)):print(line,end='')
?
class Countdown:
def __init__(self, start):
self.start = start
# Forward iterator
def __iter__(self):
n = self.start
while n > 0:
yield n
n -= 1
# Reverse iterator
def __reversed__(self):
n = 1
while n <= self.start:
yield n
n += 1for rr in reversed(Countdown(30)):
print(rr)
for rr in Countdown(30):
print(rr)
?定義一個反向迭代器可以使得代碼非常的高效,因為它不再需要將數據填充到一個列表中然后再去反向迭代這個列表。
?