-1

Suppose I have a list of list called mat of shape 5x5.

Then I initialize a "column", element by element as follows

mat[0][4] = 'X'
mat[1][4] = 'O'
mat[2][4] = 'R'
mat[3][4] = 'N'
mat[4][4] = 'A'

Is there any way to initialize this column vector in one line in Python like how MATLAB might do?

mat[:,4] = ['X','O','R','N','A']
Ignacio Vergara Kausel
  • 5,521
  • 4
  • 31
  • 41
akad3b
  • 397
  • 1
  • 3
  • 13
  • 1
    Be careful of confusing a list of lists in python with a matlab 2D matrix. If you want a more direct map to matlab, check `numpy`. Although there I'd advise against using characters as elements. – Ignacio Vergara Kausel Nov 03 '17 at 09:00
  • 1
    I would guess that this is used for some sort of traditional cipher, where a 5*5 grid of letters is common (the English alphabet has 26 letters, and an uncommon letter can be dropped/replaced according to some rule). – Imperishable Night Nov 03 '17 at 09:14

2 Answers2

1

Not quite as concise, but:

for i,x in enumerate(['X','O','R','N','A']): mat[i][4]=x

Or in the case of single characters, slightly shorter:

for i,x in enumerate('XORNA'): mat[i][4]=x

Alternatively, you can use numpy:

import numpy
mat=numpy.array([[' ' for i in range(5)] for j in range(5)])
mat[:,4] = ['X','O','R','N','A']
Imperishable Night
  • 1,503
  • 9
  • 19
  • I'd change the creation of the matrix as `mat = numpy.empty((5,5), dtype=object)`. Seems clearer that a double list comprehension. Didn't want to edit myself, as the code is not wrong ;) – Ignacio Vergara Kausel Nov 03 '17 at 09:12
-1

I had a similar problem a couple of years ago while developing a Sudoku algorithm. I had to frequently switch between columns and rows and the nested "for" where killing me.

So I came up with the easy solution to just rotate my matrix and always treat everything as a row. If optimisation is not an issue, you can do that.

Here is how to rotate a multi-dimensional array in python: Rotating a two-dimensional array in Python

sashok_bg
  • 2,436
  • 1
  • 22
  • 33