鉴于range
对象是可下标的,为什么itertools.repeat
对象不能下标?
In [10]: range(3, 10)[3]
Out[10]: 6
In [11]: import itertools as it
In [12]: it.repeat(5)[3]
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-12-1ef74480e0a7> in <module>()
----> 1 it.repeat(5)[3]
TypeError: 'itertools.repeat' object is not subscriptable
请注意,范围对象和 itertools.repeat 对象是 Python 3 的一部分。
我会比较喜欢:
class repeat_(itertools.repeat):
def __init__(self, object_, times=None):
super().__init__(object_, times)
self.object_ = object_
self.times = times
def __reversed__(self):
return self
def __getitem__(self, key):
return self.object_
def __contains__(self, key):
return key == self.object_
def __len__(self):
if self.times is None:
raise ValueError
return self.times