如何反向迭代一个列表
方式一:reverse,缺点是改变了原列表
l = [1, 2, 3, 4, 5]
l.reverse()
方式二:切片,缺点是生成了一个等大的列表,浪费内存
l = [1, 2, 3, 4, 5]
l1 = l[::-1]
方式三:reversed,得到列表的反向迭代器,作用与iter函数相反
l = [1, 2, 3, 4, 5]
l1 = reversed(l) # 等价于 l.__reversed__()
实际案例:
实现一个连续浮点数发生器FloatRange(类似range),根据给定范围(start,end)和步长(step)产生一些连续浮点数,如迭代 FloatRange(3.0, 4.0, 0.2)课产生序列:
正向:3.0 3.2 3.4 3.6 3.8 4.0
反向:4.0 3.8 3.6 3.4 3.2 3.0
class FloatRange:
def __init__(self, start, end, step=0.1):
self.start = start
self.end = end
self.step = step
def __iter__(self):
t = self.start
while round(t,2) <= self.end:
yield round(t,2)
t += self.step
def __reversed__(self):
t = self.end
while round(t,2) >= self.start:
yield round(t,2)
t -= self.step
obj = FloatRange(2.0, 3.0, 0.2)
for x in obj:
print(x) #2.0 2.2 2.4 2.6 2.8 3.0
for x in reversed(obj):
print(x) #3.0 2.8 2.6 2.4 2.2 2.0