Python中实现反向迭代一般最容易想到的就是使用步长为-1的切片操作来执行
>>> l = [1, 2, 3 ,4 ,5]
>>> l[::-1]
[5, 4, 3, 2, 1]
但是这样会产生一个与原列表一样的列表,十分浪费存储空间
reversed操作会产生一个列表的反向生成器也可以实现反向迭代而且不占用存储空间
>>> reversed(l)
<list_reverseiterator object at 0x00000000010A1A20>
>>> for x in reversed(l):
... print(x)
...
5
4
3
2
1
下面实现一个可以反向迭代的浮点数生成器类
>>> class FloatRange:
... def __init__(self, start, end, step=0.1):
... self.start = start
... self.end = end
... self.step = step
... def __iter__(self):
... start = self.start
... while start < self.end:
... yield start
... start += self.step
... def __reversed__(self):
... end = self.end
... while end > self.start:
... yield end
... end -= self.step
...
>>> f = FloatRange(1.0, 5.0, step=0.5)
>>> for x in f:
... print(x)
...
1.0
1.5
2.0
2.5
3.0
3.5
4.0
4.5
>>> for x in reversed(f):
... print(x)
...
5.0
4.5
4.0
3.5
3.0
2.5
2.0
1.5