Creating multi-dimensional arrays

Alex Martelli aleax at aleax.it
Wed Aug 8 05:30:35 EDT 2001


<spam_buster_2000 at yahoo.com> wrote in message
news:9kqupp$1jt$1 at wisteria.csv.warwick.ac.uk...
> I've been writing a couple of programs recently which use
multi-dimensional arrays of
> a predefined size, and I was wondering if there was a standard idiomatic
way of creating
> these in Python. I'm not looking to restrict the arrays to contain
specific types, so just
> pointing me to Numeric isn't the answer here.

Numeric IS the answer (or at least AN answer, and a good one:-)
because a Numeric array CAN be specified to hold arbitrary
Python objects -- use Numeric.PyObject as their type-spec.

"""it turns out that a very useful set of features of arrays
is the ability to slice them, dice them, select and choose from
them, and repeat their elements. This feature is so nice that
sometimes one wants to do the same operations with, e.g., arrays
of strings. In such cases, computation speed is not as important
as convenience.""" (http://starship.python.net/~da/numtut/array.html).


> There are two ways I've been using to create these arrays:
>
> First way (simple, pretty):
>
> >>> a = [[[0 for x in range(10)]
> ...          for y in range(10)]
> ...          for z in range(10)]
>
> Which I suppose has the advantage of documenting exactly what each
dimension indicates.
>
> Second way (more general):
>
> from copy import deepcopy
>
> def makearray(dimensions, init=None):
> if len(dimensions) == 1:
> array = [init]*dimensions[0]
> else:
> subarray = makearray(dimensions[1:], init)
> array = [deepcopy(subarray) for i in range(dimensions[0])]
>
> return array
>
> a = makearray((10,10,10), 0)
>
> I'm sure this isn't particularly efficient, though (and has no error
checking...).
>
> Is there an obvious better way I should be using (the thing that comes to
mind is a class
> which would use a 1 dimensional array and pretend to be multidimensional,
a lot like Numeric)?
>
> --
> Jon





More information about the Python-list mailing list