How to access elemenst in a list of lists?

Algis Kabaila akabaila at pcug.org.au
Tue May 10 03:22:42 EDT 2011


On Tuesday 10 May 2011 11:25:59 Terry Reedy wrote:
> On 5/9/2011 8:44 PM, Algis Kabaila wrote:
> > The method of double indexing in the manner
> > a[i][j]
> > for the (i, j) -th element of multi-dimensional array is
> > well known and widely used. But how to enable the
> > "standard" matrix notation a[i, j]
> > in Python 3.2 in the manner of numpy (and other matrix
> > packages)? Is it subclassing of "special methods"
> > 
> > __getitem__() # to get
> > 
> > __setitem__()  # to set
> 
> Yes.
> 
> 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
> 
> IMO, Hardly worth it for two dimensions.

Terry,

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?
However,  the method that you have indicated is a neat way to 
solve the problem -- thank you for it!

OldAl

PS: just to confirm your method and the limitation of it "as 
is": It is NOT a criticism, just a mere observation,  Good 
method, nice examle, great contribution!

>>> 
3 a
Showing limitation of "as is" in this
great method for access of list of lists
Traceback (most recent call last):
  File "/dat/work/linalg/dim2.py", line 15, in <module>
    print(ll[1])
  File "/dat/work/linalg/dim2.py", line 6, in __getitem__
    i,j = dex
TypeError: 'int' object is not iterable
>>> 
-- 
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/ced18e5c/attachment-0001.html>


More information about the Python-list mailing list