反向迭代器

要实现一个反向迭代器其实非常简单,只需实现 __reversed__ 这个特殊方法即可,它会被 python 内置的 reversed 函数所调用。反向迭代器在数据量很多时可以改善代码性能,因为它不需要把数据填充到一个列表中然后再去反向迭代该列表。
下面这个示例是对内置函数 range 的简单模拟:

class Countdown:
def __init__(self, start, stop, step=1):
if not (isinstance(start, int) and isinstance(stop, int) and isinstance(step, int)):
raise TypeError("All arguments need to be integers.")
self._start = start
self._stop = stop
self._step = step

def __iter__(self):
n = self._start
if self._step > 0:
while n < self._stop:
yield n
n += self._step
else:
while n > self._stop:
yield n
n += self._step
raise StopIteration

def __reversed__(self):
return Countdown(self._stop-1, self._start-1, -self._step)

运行示例:

>>> for i in Countdown(1.1, 8.2):
print(i)

Traceback (most recent call last):
File "<pyshell#53>", line 1, in <module>
for i in Countdown(1.1, 8.2):
File "<pyshell#50>", line 4, in __init__
raise TypeError("All arguments need to be integers.")
TypeError: All arguments need to be integers.
>>>
>>> for i in Countdown(1, 8, 2):
print(i)

1
3
5
7
>>>
>>> for i in reversed( Countdown(1, 8, 2) ):
print(i)

7
5
3
1
>>>

这里之所以限制参数为整数而非任意实数,主要是因为浮点数的精度问题会让代码变得比较臃肿。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值