Python中的多维数组 [英] Multidimensional array in Python

查看:78
本文介绍了Python中的多维数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Java小问题,想翻译成Python.因此,我需要一个多维数组.在Java中,它看起来像:

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.

如何实例化数组?

PS:不涉及矩阵乘法...

PS: There is no matrix multiplication involved...

推荐答案

您可以使用嵌套列表来创建它:

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]

可以这样使用:

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

可以这样使用:

m = Matrix(4,5,2,6)
m[2,3,1,3] = 'x'
m[2,3,1,3] // -> 'x'

这篇关于Python中的多维数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆