Python多维数组作为单个Lis

2024-05-05 17:17:47 发布

您现在位置:Python中文网/ 问答频道 /正文

当然,可以使用嵌套列表来表示多维数组,但这似乎很昂贵。。。在

[[0, 1], [2, 3]]

有没有办法把坐标“编码”和“解码”成一个数字,然后用这个数字来查找相应的元素?在

^{pr2}$

这需要使用n维,而不仅仅是2维,我能想到的最好的编码方法是:

def getcellindex(self, location):
  cindex = 0
  cdrop = self.gridsize # where self.gridsize is the number of cells
  for index in xrange(self.numdimensions): # where self.numdimensions is the number of dimensions
    # where self.dimensions is a tuple of the different sizes of the corresponding dimension
    cdrop /= self.dimensions[index]
    cindex += cdrop * location[index]
  return cindex

可能有一些方法可以优化这一点,但更重要的是,我如何逆转这个过程?还有,这个功能有用吗?在


Tags: oftheselfnumber列表indexis数字
3条回答

如果你想要快速的阵列,你可能会想要看到非常快的纽比阵列。否则,如果你有尺寸n1,n2,n3,…,nm,那么你可以编码a[i][j][k]…[r]:i*(n2,n3……)的乘积j*(n3,n4…)的乘积)+r。相反的操作你必须得到nm的模,那就是r,然后你必须减去r,找到nm*n(m-1)的模,依此类推。在

def getlocation(self, cellindex):
    res = []
    for size in reversed(self.dimensions):
        res.append(cellindex % size)
        cellindex /= size
    return res[::-1]

或者,对于完整的测试用例

^{pr2}$

你是否因为担心它的性能而回避了显而易见的答案(即[[1, 2], [3, 4]])?{看,如果你在工作。最好的解决办法是不要重新发明你自己的轮子。在

编辑: 如果你真的觉得有必要用你自己的方式来做,你可以像NumPy一样遵循一个strided index scheme的方式,wihch可能会这样做:

import operator
def product(lst):
    return reduce(operator.mul, lst, 1)

class MyArray(object):
    def __init__(self, shape, initval):
        self.shape = shape
        self.strides = [ product(shape[i+1:]) for i in xrange(len(shape)) ]
        self.data = [initval] * product(shape)

    def getindex(self, loc):
        return sum([ x*y for x, y in zip(self.strides, loc) ])

    def getloc(self, index):
        loc = tuple()
        for s in self.strides:
            i = index // s
            index = index % s
            loc += (i,)
        return loc

用作:

^{pr2}$

相关问题 更多 >