Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #5060

Re: How to access elemenst in a list of lists?

From Terry Reedy <tjreedy@udel.edu>
Subject Re: How to access elemenst in a list of lists?
Date 2011-05-10 03:44 -0400
References <4dc75c67$0$29896$c3e8da3$5496439d@news.astraweb.com> <201105101044.28593.akabaila@pcug.org.au> <iqa474$a7h$1@dough.gmane.org> <201105101722.42524.akabaila@pcug.org.au>
Newsgroups comp.lang.python
Message-ID <mailman.1375.1305013502.9059.python-list@python.org> (permalink)

Show all headers | View raw


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

Back to comp.lang.python | Previous | NextPrevious in thread | Find similar


Thread

How to access elemenst in a list of lists? Chris Roy-Smith <chris_roysmith.nothere@internode.on.net> - 2011-05-09 03:15 +0000
  Re: How to access elemenst in a list of lists? Chris Angelico <rosuav@gmail.com> - 2011-05-09 13:23 +1000
  Re: How to access elemenst in a list of lists? James Mills <prologic@shortcircuit.net.au> - 2011-05-09 13:31 +1000
    Re: How to access elements in a list of lists? Chris Roy-Smith <chris_roysmith@internode.on.net> - 2011-05-09 14:40 +1000
  Re: How to access elemenst in a list of lists? Antonio CHESSA<4aedc00f81024@poster.grepler.com> - 2011-05-09 08:25 +0000
    Re: How to access elemenst in a list of lists? Terry Reedy <tjreedy@udel.edu> - 2011-05-09 15:24 -0400
    Re: How to access elemenst in a list of lists? Terry Reedy <tjreedy@udel.edu> - 2011-05-09 21:25 -0400
  Re: How to access elemenst in a list of lists? Terry Reedy <tjreedy@udel.edu> - 2011-05-10 03:44 -0400

csiph-web