Skip to content
Advertisement

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…

Advertisement

Answer

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'
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement