簡體   English   中英

如何將 map 線性索引到 python 中列表數組的二維索引?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM