用另一个基于python索引的列表的值替换列表列表列表中的值

用另一个基于python索引的列表的值替换列表列表列表中的值,python,arrays,python-3.x,Python,Arrays,Python 3.x,具体清单如下: mainList = [[0, 2, 1, 4, 3], [0, 2, 1, 3, 4], [1, 0, 2, 3, 4], [2, 1, 0, 3, 4], [1, 0, 2, 3, 4], [0, 1, 2 ,3, 4], [0, 2, 1, 3, 4]] mainList_mapped = [[0.0, 0.4, 0.2, 0.9, 0.4], [0.0, 0

具体清单如下:

mainList = [[0, 2, 1, 4, 3],
       [0, 2, 1, 3, 4],
       [1, 0, 2, 3, 4],
       [2, 1, 0, 3, 4],
       [1, 0, 2, 3, 4],
       [0, 1, 2 ,3, 4],
       [0, 2, 1, 3, 4]]
mainList_mapped = [[0.0, 0.4, 0.2, 0.9, 0.4],
               [0.0, 0.4, 0.2, 0.4, 0.9],
               [0.2, 0.0, 0.4, 0.4, 0.9],
               [0.4, 0.2, 0.0, 0.4, 0.9],
               [0.2, 0.0, 0.4, 0.4, 0.9],
               [0.0, 0.2, 0.4, 0.4, 0.9],
               [0.0, 0.4, 0.2, 0.4, 0.9]]
列表索引=[0,1,2,3,4],列表值=[0.0,0.2,0.4,0.4,0.9]

所需清单如下:

mainList = [[0, 2, 1, 4, 3],
       [0, 2, 1, 3, 4],
       [1, 0, 2, 3, 4],
       [2, 1, 0, 3, 4],
       [1, 0, 2, 3, 4],
       [0, 1, 2 ,3, 4],
       [0, 2, 1, 3, 4]]
mainList_mapped = [[0.0, 0.4, 0.2, 0.9, 0.4],
               [0.0, 0.4, 0.2, 0.4, 0.9],
               [0.2, 0.0, 0.4, 0.4, 0.9],
               [0.4, 0.2, 0.0, 0.4, 0.9],
               [0.2, 0.0, 0.4, 0.4, 0.9],
               [0.0, 0.2, 0.4, 0.4, 0.9],
               [0.0, 0.4, 0.2, 0.4, 0.9]]
主列表的值将被视为索引,并由列表中的相应索引值替换。我试过了,但代码不起作用

mainList_mapped = []

for ls in mainList:
    for (i, j) in zip(ls, list_value):
        ls[i] = j
    
    mainList_mapped.append(ls)

这里有一个类似的答案,但我在得到结果时遇到了错误(TypeError:列表索引必须是整数或切片,而不是浮点)。任何帮助都将不胜感激。

您可以创建一个函数,根据给定的索引重新排列列表:

def rearrange(value, indices):
    return [value[i] for i in indices]
现在将此功能应用于mainlist中的所有列表:

>>> result = [rearrange(list_value, indices) for indices in mainList]
>>> result
[[0.0, 0.4, 0.2, 0.9, 0.4],
 [0.0, 0.4, 0.2, 0.4, 0.9],
 [0.2, 0.0, 0.4, 0.4, 0.9],
 [0.4, 0.2, 0.0, 0.4, 0.9],
 [0.2, 0.0, 0.4, 0.4, 0.9],
 [0.0, 0.2, 0.4, 0.4, 0.9],
 [0.0, 0.4, 0.2, 0.4, 0.9]]
在这种情况下更容易,因为
list\u索引
是排序的,但是如果它被洗牌,您可以像这样更改重排函数:

mapping = dict(zip(list_indices, list_value))

def rearrange(mapping, indices):
    return [mapping[i] for i in indices]
mainList_mapped = []
for row in mainList:
    row_mapped = []
    for index in row:
        row_mapped.append(list_value[index])
    mainList_mapped.append(row_mapped)

你应该这样做:

mapping = dict(zip(list_indices, list_value))

def rearrange(mapping, indices):
    return [mapping[i] for i in indices]
mainList_mapped = []
for row in mainList:
    row_mapped = []
    for index in row:
        row_mapped.append(list_value[index])
    mainList_mapped.append(row_mapped)

尝试使用嵌套列表:

print([[list_value[x] for x in i] for i in mainList])
输出:

[[0.0, 0.4, 0.2, 0.9, 0.4], [0.0, 0.4, 0.2, 0.4, 0.9], [0.2, 0.0, 0.4, 0.4, 0.9], [0.4, 0.2, 0.0, 0.4, 0.9], [0.2, 0.0, 0.4, 0.4, 0.9], [0.0, 0.2, 0.4, 0.4, 0.9], [0.0, 0.4, 0.2, 0.4, 0.9]]