[英]How to map a linear index to 2D index for array of list in python?
我得到了一堆用于访问列表数组的线性索引。 每个列表的大小不同。 例如
data = [[1,2,3,4,5,6], # L1
[2,3,4,5], # L2
[1,2,3], # L3
[7,9,10,11,18,22,1,3]] # L4
让我将第一个列表(在顶部)称为 L1,将第二个列表称为 L2,依此类推。 给定一个线性索引以一次获取由每个列表的一个元素组成的数组的视图。
例如,
linear-index view
0 L1[0], L2[0], L3[0], L4[0]
1 L1[0], L2[0], L3[0], L4[1]
2 L1[0], L2[0], L3[0], L4[2]
3 L1[0], L2[0], L3[0], L4[3]
k(k<len(L4) L1[0], L2[0], L3[0], L4[k]
m=len(L4) L1[0], L2[0], L3[1], L4[0]
m=len(L4)+3 L1[0], L2[0], L3[1], L4[3]
线性索引沿着最后一个列表向第一个列表移动。 我知道如果数组是矩形的,使得每个列表具有相同的长度,我可以使用 numpy 的 unravel_index 来提取 2d 索引。 为了测试它,我假设一个包含 2 个列表的数组,每个列表的长度为 3
data = [[1,2,3],[4,5,6]]
共有9个线性索引,0、1、2、3、4、5、6、7、8对应条目列表(值)
0 => [1,4]
1 => [1,5]
2 => [1,6]
3 => [2,4]
4 => [2,5]
5 => [2,6]
6 => [3,4]
7 => [3,5]
8 => [3,6]
我没有找到更好的映射方法,所以我通过迭代所有数据来构建映射
data = [[1,2,3],[4,5,6]]
idx2d = 0
idxmap = dict()
meters = [0]*len(data) # use to remember the pointer of the current position of each list
totalNumIndices = 1
for row in data:
totalNumIndices *= len(row) # total number of linear indices could be
for idx2d in range(totalNumIndices):
dd = []
for n in range(0, len(data)):
dd.append(data[n][meters[n]])
idxmap[idx2d] = dd
meters[len(data)-1] += 1
for row in range(len(data)-2,-1,-1): # reverse the oder because the last list on the bottom will be access first
if (meters[row+1] >= len(data[row+1])):
meters[row] += 1
meters[row+1] = 0
它似乎工作。 但是,我给的实际数据非常大,提前建立这样的映射是不切实际的。 我正在寻找某人的建议,以获得更好的算法来计算具有给定线性索引的映射。
如果我正确理解了这个问题,以下应该可以工作:
import itertools
data = [[1,2,3],[4,5,6]]
dict(enumerate(itertools.product(*data)))
它给:
{0: (1, 4),
1: (1, 5),
2: (1, 6),
3: (2, 4),
4: (2, 5),
5: (2, 6),
6: (3, 4),
7: (3, 5),
8: (3, 6)}
由于enumerate(itertools.product(*data))
返回一个迭代器,它可以一次构建一个元素的映射,而不是一次计算所有元素。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.