Home > Back-end >  Matrix (list) in python
Matrix (list) in python

Time:04-27

I want to create a matrix ROW x COLS based on another matrix original size ROW x COLS.

ROWS = len(mat)
COLS = len(mat[0])
    
res = [[0 for i in range(ROWS)] for i in range(COLS)]

The above code doesn't work for the following edge case:

mat = [[3],[4],[5],[5],[3]]

My desired output is:

[[0],[0],[0],[0],[0]]

However, what I get is:

[[0,0,0,0,0]]

How can I adapt my code to work with any case? ( I do not want to use numpy or any other libraries)

CodePudding user response:

Swap the ROWS and COLS like so:

res = [[0 for i in range(COLS)] for i in range(ROWS)]

CodePudding user response:

Try:

>>> [[0 for i in range(len(mat[0]))] for j in range(len(mat))]
[[0], [0], [0], [0], [0]]

Also better to use different loop variables instead of i for both:

CodePudding user response:

`
mat = [[3],[4],[5],[5],[3]]
ROWS = len(mat)
COLS = len(mat[0])

res = [[[0] for i in range(ROWS)] for i in range(COLS)]
res = res[0]
res
`
  • Related