Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multidimensional array in Python

I have a little Java problem I want to translate to Python. Therefor I need a multidimensional array. In Java it looks like:

double dArray[][][] = new double[x.length()+1][y.length()+1][x.length()+y.length()+3];
dArray[0][0][0] = 0;
dArray[0][0][1] = POSITIVE_INFINITY;

Further values will be created bei loops and written into the array.

How do I instantiate the array?

PS: There is no matrix multiplication involved...

like image 487
Christian Stade-Schuldt Avatar asked Feb 03 '09 19:02

Christian Stade-Schuldt


People also ask

What is multidimensional array and example?

A multi-dimensional array is an array with more than one level or dimension. For example, a 2D array, or two-dimensional array, is an array of arrays, meaning it is a matrix of rows and columns (think of a table). A 3D array adds another dimension, turning it into an array of arrays of arrays.

Is NumPy array multidimensional?

NumPy is a general-purpose array-processing package. It provides a high-performance multidimensional array object and tools for working with these arrays.


2 Answers

You can create it using nested lists:

matrix = [[a,b],[c,d],[e,f]]

If it has to be dynamic it's more complicated, why not write a small class yourself?

class Matrix(object):
    def __init__(self, rows, columns, default=0):
        self.m = []
        for i in range(rows):
            self.m.append([default for j in range(columns)])

    def __getitem__(self, index):
        return self.m[index]

This can be used like this:

m = Matrix(10,5)
m[3][6] = 7
print m[3][6] // -> 7

I'm sure one could implement it much more efficient. :)

If you need multidimensional arrays you can either create an array and calculate the offset or you'd use arrays in arrays in arrays, which can be pretty bad for memory. (Could be faster though…) I've implemented the first idea like this:

class Matrix(object):
    def __init__(self, *dims):
        self._shortcuts = [i for i in self._create_shortcuts(dims)]
        self._li = [None] * (self._shortcuts.pop())
        self._shortcuts.reverse()

    def _create_shortcuts(self, dims):
        dimList = list(dims)
        dimList.reverse()
        number = 1
        yield 1
        for i in dimList:
            number *= i
            yield number

    def _flat_index(self, index):
        if len(index) != len(self._shortcuts):
            raise TypeError()

        flatIndex = 0
        for i, num in enumerate(index):
            flatIndex += num * self._shortcuts[i]
        return flatIndex

    def __getitem__(self, index):
        return self._li[self._flat_index(index)]

    def __setitem__(self, index, value):
        self._li[self._flat_index(index)] = value

Can be used like this:

m = Matrix(4,5,2,6)
m[2,3,1,3] = 'x'
m[2,3,1,3] // -> 'x'
like image 121
Georg Schölly Avatar answered Sep 29 '22 04:09

Georg Schölly


To create a standard python array of arrays of arbitrary size:

a = [[0]*cols for _ in [0]*rows]

It is accessed like this:

a[0][1] = 5 # set cell at row 0, col 1 to 5

A small python gotcha that's worth mentioning: It is tempting to just type

a = [[0]*cols]*rows

but that'll copy the same column array to each row, resulting in unwanted behaviour. Namely:

>>> a[0][0] = 5
>>> print a[1][0]
5
like image 43
Deestan Avatar answered Sep 29 '22 06:09

Deestan