[Python-ideas] Add a datatype collections.ListView
Terry Reedy
tjreedy at udel.edu
Thu Apr 17 20:12:07 CEST 2014
On 4/17/2014 11:49 AM, David Mertz wrote:
> What I'd really like is a "ListView" that acts something like NumPy's
> non-copying slices.
Consider a more generic SeqView, especially if you do not intend to
mutate through the view. I also suggest that you use a range object
instead of .start, .stop, (and .step). Range gives you a lot for free,
including slicing. Untested:
class SeqView:
def __init__(self, seq, rng)
self.seq = seq
self.rng = rng
def __getitem__(self, index):
if isinstance(index, slice):
return Seqview(self.seq, self.rng[index])
else:
return self.seq[self.rng[index]] # see below
def __iter__(self):
seq, rng = self.seq, self.rng
for i in rng:
yield seq[i]
...
>>> r = range(3, 50, 3)
>>> r[4]
15
>>> r[500]
Traceback (most recent call last):
File "<pyshell#2>", line 1, in <module>
r[500]
IndexError: range object index out of range
# You would want to catch this and change 'range' to SeqView
>>> r[1:3]
range(6, 12, 3)
>>> r[slice(1,3)]
range(6, 12, 3)
>>> r[slice(1,3,2)]
range(6, 12, 6)
--
Terry Jan Reedy
More information about the Python-ideas
mailing list