Creating multi-dimensional arrays
Lloyd Goldwasser
goldwasser at demog.berkeley.edu
Wed Aug 8 16:47:11 EDT 2001
spam_buster_2000 at yahoo.com wrote:
>
> 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.
Here's something I use:
def nestedList(dimens, value=None):
"""Return a list of unique copies of value,
nested according to the positive integers in dimens."""
if len(dimens)==0:
return value
else:
return [ nestedList(dimens[1:], value) for i in range(dimens[0]) ]
The first argument is a list of the lengths along each dimension; your
example would be nestedList([10,10,10], 0). It works with any types:
>>> nestedList([3,2,5], 'aoe')
[[['aoe', 'aoe', 'aoe', 'aoe', 'aoe'], ['aoe', 'aoe', 'aoe', 'aoe',
'aoe']], [['aoe', 'aoe', 'aoe', 'aoe', 'aoe'], ['aoe', 'aoe', 'aoe',
'aoe', 'aoe']], [['aoe', 'aoe', 'aoe', 'aoe', 'aoe'], ['aoe', 'aoe',
'aoe', 'aoe', 'aoe']]]
I suppose that the recursion isn't especially idiomatic (if you guessed
that this routine is a Python translation of something I originally
wrote in Scheme, you'd be right, but it's nice that the Python version
is shorter and clearer than the original). As the number of dimensions
gets up around a dozen, things slow down a bit, but then you're working
with lots of elements.
Lloyd
--
Lloyd Goldwasser Department of Demography
goldwasser at demog.berkeley.edu 2232 Piedmont Ave. #2120
(510) 642-0525 University of California
fax: (510) 643-8558 Berkeley, CA 94720-2120
More information about the Python-list
mailing list