defining multi dimensional array

Nick Craig-Wood nick at craig-wood.com
Wed Jul 5 03:30:03 EDT 2006


bruce <bedouglas at earthlink.net> wrote:
>  i need a multi dimensional array of lists...
> 
>   ie 
>    [q,a,d]
>    [q1,a1,d1]
>    [q2,a2,d2]
>    [q3,a3,d3]
> 
>  which would be a (3,4) array...

Multi-dimensional arrays aren't a built in feature of python.

You can simulate them two ways

1) with a list of lists

>>> a = [
...   [1,2,3],
...   [4,5,6],
...   [7,8,9],
...   [10,11,12]
... ]
>>> 
>>> print a[1][1]
5
>>> a[2][1] = 'hello'
>>> print a
[[1, 2, 3], [4, 5, 6], [7, 'hello', 9], [10, 11, 12]]

2) using a hash

>>> a = {}
>>> i = 1
>>> for x in range(4):
...     for y in range(3):
...         a[x,y] = i
...         i = i + 1
... 
>>> print a[1,1]
5
>>> a[2,1] = 'hello'
>>> print a
{(3, 2): 12, (3, 1): 11, (1, 2): 6, (1, 1): 5, (3, 0): 10, (0, 2): 3, (1, 0): 4, (0, 0): 1, (0, 1): 2, (2, 0): 7, (2, 1): 'hello', (2, 2): 9}
>>> 

Option 1) is the normal way of doing it in python.  However
initialising a multidimensional array always trips over beginners.  Do
it like this, where 0 is the initial value.

>>> a = [ [ 0 for y in range(3)] for x in range(4) ]
>>> print a
[[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]]

Once you've done that you can write

>>> a = [ [ 0 for y in range(3)] for x in range(4) ]
>>> i = 1
>>> for x in range(4):
...     for y in range(3):
...         a[x][y] = i
...         i = i + 1
... 
>>> print a[1][1]
5
>>> a[2][1] = 'hello'
>>> print a
[[1, 2, 3], [4, 5, 6], [7, 'hello', 9], [10, 11, 12]]

Numeric/scipy/numpy/whatever-it-is-called-today supports
multidimensional arrays too I think and that may be more appropriate
if you are doing heavy numerical work.

-- 
Nick Craig-Wood <nick at craig-wood.com> -- http://www.craig-wood.com/nick



More information about the Python-list mailing list