My first stumbling block with Python

Bengt Richter bokr at oz.net
Fri Aug 23 21:03:34 CEST 2002


On Thu, 22 Aug 2002 09:12:52 -0400, "Mr. Neutron" <nicktsocanos at charter.net> wrote:

>Sigh, it was too good to be true. I have come across my first problem
>with Python programming.
>
>Python does not seem to have an Array type. It has the Array object,
>which is a one dimensional array, and it works fine. However, I need a
>two dimensional array mapped (X,Y) of tuples.
>
>I can think of ways to do this in the language, by creating a list of all
>the elements, and creating a function def GetPos(X,Y) that maps into the
>list and gets the element. The math isn't too hard off the top of my head
>it is like
>	GetPos(X,Y):
>		return list[ (Y * RowSize) + X ]
>
>	and SetPos(X,Y, MyTuple)
>		list[ (Y*RowSize) + X ] = MyTuple
>
>Where RowSize is the width of the array.
>
>Now the question is, are there any easier or better ways to get a two
>dimensional array of tuples in Python
>
>Something like 
>
>		MyArray[X][Y] = (tuple)

If you are just dealing with doubles (and ints which you don't mind getting converted to doubles)
you could do something simple like:

 >>> import array
 >>> class My2D:
 ...     def __init__(self, cols, rows):
 ...         self.rows = rows
 ...         self.cols = cols
 ...         self.arr  = array.array('d',[0.0]*rows*cols*2)
 ...     def __getitem__(self, col_row):
 ...         c,r = col_row
 ...         i = (r*self.cols+c)*2
 ...         return self.arr[i], self.arr[i+1]
 ...     def __setitem__(self, col_row, xy):
 ...         c,r = col_row
 ...         i = (r*self.cols+c)*2
 ...         self.arr[i] = xy[0]
 ...         self.arr[i+1] = xy[1]
 ...
 >>> a = My2D(3,5)
 >>> for c in xrange(3):
 ...     for r in xrange(5):
 ...         a[c,r] = c*10,r*10
 ...
 >>> a[2,3]
 (20.0, 30.0)
 >>> a[1,4]
 (10.0, 40.0)
 >>> a[2,4]
 (20.0, 40.0)
 >>> a[1,2]
 (10.0, 20.0)
 >>> a[2,1]
 (20.0, 10.0)
 >>> a[2,3]
 (20.0, 30.0)
 >>> a[2,3] = (-2.5,3.5)
 >>> a[2,3]
 (-2.5, 3.5)
 >>> a[1,2] = -1.5, 2.5
 >>> a[1,2]
 (-1.5, 2.5)


(Not tested beyond what you see ;-)

You could enhance __[gs]etitem__ to deal with slices also if desired.

Regards,
Bengt Richter



More information about the Python-list mailing list