arrays

Carl Banks imbosol at aerojockey.com
Thu Nov 18 00:14:19 EST 2004


codedivine at gmail.com (Rahul Garg) wrote in message news:<a2f50cd.0411151042.45487164 at posting.google.com>...
> Hi.
> Is there someway i can get something similar to multi-dimensional
> arrays in python.I dont want to use Numarray.
> rahul

It seems (from other posts) as if you're looking for a way to get
simple multidimensional array behavior in Python, while making
convenient to access it in C, without using numarray or Numeric.

Probably the simplest way to accomplish this without numarray is to
use a class to wrap a list.  Override __getitem__ and __setitem__ to
get the effect of multidimensional access.  Because the data is stored
in a single list, rather than a list of lists, it is convenient to
access it from C.  A minimal example follows.

    class MinimalMultiArray:
        def __init__(self,rows,cols):
            self.rows = rows
            self.cols = cols
            self.data = [0.0] * self.rows * self.cols
        def __getitem__(self,(row,column)):
            return self.data[row*self.cols + column]
        def __setitem__(self,(row,column),value):
            self.data[row*self.cols + column] = value

Notice that Python can unwrap tuples right into function arguments, so
if you reference array[1,2], in __getitem__, row will be set to one
and column to two.

Any improvements left as an exercise.  Here's a suggestion: check
whether row and column arguments are slice objects, and return a list
or a smaller multidimensional array if so.


-- 
CARL BANKS



More information about the Python-list mailing list