python迭代-如何实现反向迭代

如何实现反向迭代

问题举例

实现一个连续浮点数发生器FloatRange,根据给定范围(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

分析

(1)列表的reverse()方法

list1 = [1, 2, 3, 4, 5]
list1.reverse()
for x in list1:
    print(x) # 5 4 3 2 1

改变了原列表,在某些情况下是不被允许的

(2)切片操作

list1 = [1, 2, 3, 4, 5]
list2 = list1[::-1]
for x in list2:
    print(x) # 5 4 3 2 1

创建和原列表等大的列表,浪费内存空间

解决思路

实现反向迭代协议的__reversesd__方法,它返回一个反向迭代器

代码

from decimal import Decimal

class FloatRange:
    def __init__(self, a, b, step):
        self.a = Decimal(str(a))
        self.b = Decimal(str(b))
        self.step = Decimal(str(step))

    def __iter__(self):
        t = self.a
        while t <= self.b:
            yield float(t)
            t += self.step

    def __reversed__(self):
        t = self.b
        while t >= self.a:
            yield float(t)
            t -= self.step

fr = FloatRange(3.0, 4.0, 0.2)
for x in fr:
    print(x)
print('-' * 20)
for x in reversed(fr):
    print(x)

参考资料:python3实用编程技巧进阶

原文地址:https://www.cnblogs.com/marton/p/10771608.html