How to access elemenst in a list of lists?
Terry Reedy
tjreedy at udel.edu
Tue May 10 03:44:44 EDT 2011
On 5/10/2011 3:22 AM, Algis Kabaila wrote:
> On Tuesday 10 May 2011 11:25:59 Terry Reedy wrote:
> > class listwrap:
> > def __init__(self, lis):
> > self._list = lis
> > def __getitem__(self, dex):
> > i,j = dex
> > return self._list[i][j]
>
> > # __setitem__: exercise for reader
> > l = listwrap([[1,2,3],['a','b','c']])
> > print(l[0,2],l[1,0])
> > # 3 a
> Thank you for your response. I have to confess that I do have the cludge
> of an answer to my own quesion, but it is a cludge; Your method looks
> much better, though I don't think it is complete - this subclassing of
> __getitem__ appears to stop simple list access, i.e. if li = [1, 2 ,3],
> it seems to me that print(li[2]) would raise an exception, no?
Yes, there really should be a guard condition: if isinstance(x tuple)
or try: len(x) == 2. A __getattr__ method could be added to forwar other
list methods to the wrapped list. One could try subclassing instead of
wrapping, but some special methods have a fast path access for builtins
that bypasses subclass methods. I think __getitem__ may be one such.
Wrapping is safe in that respect.
--
Terry Jan Reedy
More information about the Python-list
mailing list