How to access elemenst in a list of lists?

Algis Kabaila akabaila at pcug.org.au
Tue May 10 07:11:09 EDT 2011


On Tuesday 10 May 2011 17:44:44 Terry Reedy wrote:
> 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.

Actually, I am working on an array class that subclasses list. 
My interest is to have a module that deals with matrices with 
pure Python 3.2 or higher.  The class would need to deal with 
many different arrays and matrix operations between them.

In since Array subclasses list, any modifications of __getitem__ 
ir __setitem__ would naturally be in the array class and would 
in fact subclass the list special methods if implemented in the 
Array class.  And, to my chagrin, I do manage to mess it up...

Thanks for your bright suggestion,

OldAl.

-- 
Algis
http://akabaila.pcug.org.au/StructuralAnalysis.pdf
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20110510/dd842d54/attachment-0001.html>


More information about the Python-list mailing list