如何按正确的列位置重新排序字段?

How to reorder fields by right columns positions?

有 header 个 table 的正确位置:

arr = [1,2,3,4,5,6]

还有一个矩阵(rowsxcols):

matrix = [
    [2,3,4], 
    [1,3,6], 
    [2,4,5]]

我尝试创建一个新矩阵,其中 matrix 的所有元素都在 arr 的正确位置。 结果我想得到这个矩阵:

new_matrix = [[0,2,3,4,0,0],
              [1,0,3,0,0,6],
              [0,2,0,4,5,0]

我的完整代码是:

arr = [1,2,3,4,5,6]
matrix = [
    [2,3,4], 
    [1,3,6], 
    [2,4,5]]
rows = len(matrix)
summator = {}
positions = {}

for i in range(rows):
    cols = len(matrix[i])
    
    if i > 0:
        matrix[i] = matrix[i] + [0] * (len(matrix[i - 1]) - cols);
    
    for j in range(cols):
        if j not in summator:
            summator[j] = matrix[i][j]
        else:
            summator[j] += matrix[i][j]
        
        positions[j] = (summator[j] == (j + 1) * rows)


new_matrix = [[]]

for i in range(rows):
    row = []
    cols = len(matrix[i])
    
    for j in range(cols):
        if j in positions and positions[j] == True:
            row.insert(j, matrix[i][j])
            continue
        
        columnHeaderValue = arr[j]
        columnValue = matrix[i][j]
        diff  = columnValue - columnHeaderValue
        
        if diff > 0:
            print("Move right: " + str(matrix[i][j]))
            row.insert(j, 0)
            row.insert(j + 1, matrix[i][j])
    new_matrix.append(row)
    
print(new_matrix)

我在尝试创建新矩阵时遇到问题:

new_matrix = [[]]
        

您可以使用简单的列表理解来解决这个问题:

sets = [set(l) for l in matrix]
# [{2, 3, 4}, {1, 3, 6}, {2, 4, 5}]

new_matrix = [[e if e in s else 0 for e in arr] for s in sets]

注意。为了提高效率,我首先将矩阵转换为集合(in 运算符对于集合来说是 O(1),对于列表来说是 O(n))。您可以使用 matrix 代替 sets,它会起作用,只是效率较低。

输出:

[[0, 2, 3, 4, 0, 0],
 [1, 0, 3, 0, 0, 6],
 [0, 2, 0, 4, 5, 0]]