实际案例:
- 实现一个连续浮点数发生器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
通常情况下,反向一个列表会使用一下方法:
L = [1,2,3,4,5]
L.reverse()
通过以上两行代码,就将L进行了反序操作。
但是有某些情景,不允许改变L,并获取它的反向列表。
L[::-1]
通过以上代码同样可以在不改变原列表的情况下获得它的反向列表。
但是这样会得到一个新列表,在内存角度上看,也是很浪费的。
推荐方式:
使用内置函数reversed():
reversed(L)
使用此函数将会得到列表的反向迭代器。
for x in reversed(L):
print(x)
实现代码:
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
def __reversed__(self):
t = self.end
while t >= self.start:
yield t
t -= self.step
for x in FloatRange(1.0,4.0,0.5):
print(x)
for x in reversed(FloatRange(1.0,4.0,0.5)):
print(x)
网友评论