【发布时间】:2011-01-18 21:47:04
【问题描述】:
当然,您可以使用嵌套列表来表示多维数组,但这似乎代价高昂...
[[0, 1], [2, 3]]
有没有办法将坐标“编码”和“解码”成一个数字,并使用该数字来查找相应的元素?
[0, 1, 2, 3]
这需要处理 n 维,而不仅仅是两个,我能想到的最好的编码是:
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
可能有一些方法可以优化这一点,但更重要的是,我该如何扭转这个过程?还有,这个功能有用吗?
【问题讨论】:
-
“看起来很昂贵”?这只是过早的优化吗?
-
我会使用 numpy,但我需要它在 64 位 python 上工作,这似乎不适合我。
-
为什么看起来很贵?您是否测试过并发现它很慢?这个问题的聪明答案可能最终会比嵌套列表慢。
标签: python list multidimensional-array