l = [1, 2, 3, 4, 5]
l.reverse() # 翻转后,源列表也被修改
l = [1, 2, 3, 4, 5]
print(l[::-1]) # 切片逆序法,不会修改数据源,但是会生成一个等大的list,造成浪费
# 推荐reversed方法,reversed(list)方法会生成一个Iterator对象,不会修改原对象,也不会生成list占用存储空间
for x in reversed(l):
print(x)
print(l)
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 t <= self.end:
yield t
t += self.step
# 重写reversed方法
def __reversed__(self):
t = self.end
while t >= self.start:
yield t
t -= self.step
for x in reversed(FloatRange(1.0, 4.0, 0.5)):
print(x)