Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reorder fields by right columns positions?

Tags:

python

There is a header of table with right positions:

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

Also there is a matrix (rowsxcols):

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

I try to create a new matrix where all elements of matrix in right positions by arr. As result I want to get this matrix:

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

My full code is:

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)

I have issues in place where I try to create a new matrix:

new_matrix = [[]]
        
like image 403
Natalia Avatar asked Dec 17 '25 15:12

Natalia


1 Answers

You can approach this using a simple list comprehension:

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]

NB. I first converted the matrix to sets here for efficiency (the in operator is O(1) for sets, O(n) for lists). You can use matrix in place of sets, it will work, just less efficiently.

output:

[[0, 2, 3, 4, 0, 0],
 [1, 0, 3, 0, 0, 6],
 [0, 2, 0, 4, 5, 0]]
like image 122
mozway Avatar answered Dec 20 '25 06:12

mozway



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!