2

I was solving some problems at geeksforgeeks and I came across a particluar question where the inputs are provided in the test case as shown:

2 2           # denotes row, column of the matrix
1 0 0 0       # all the elements of the matrix in a single line separated by a single space.

I am not getting how to initialize my 2D array with the inputs given in such a manner.

P.S. I can't use split as it will split all the elements on in a single array from which I have to read again each element. I am looking for more simple and pythonic way.

enterML
  • 2,110
  • 4
  • 26
  • 38
  • Related: [How to input matrix (2D list) in Python?](https://stackoverflow.com/questions/22741030/how-to-input-matrix-2d-list-in-python) – Georgy Jul 12 '19 at 10:10

2 Answers2

2

You should use .split. And you also need to convert the split string items to int. But you can do that very compactly, if you want to:

rows, cols = map(int, input('rows cols: ').split())
data = map(int, input('data: ').split())
mat = [*map(list, zip(*[data] * cols))]
print(rows, cols)
print(mat)

demo

rows cols: 2 2
data: 1 2 3 4
2 2
[[1, 2], [3, 4]]

If you get a SyntaxError on mat = [*map(list, zip(*[data] * cols))] change it to

mat = list(map(list, zip(*[data] * cols)))

Or upgrade to a newer Python 3. ;)

PM 2Ring
  • 54,345
  • 6
  • 82
  • 182
0

After using split on both strings:

n_rows, n_cols = [int(x) for x in matrix_info_str.split(' ')]
split_str = matrix_str.split(' ')

I'd got with:

matrix = [split_str[i : i + n_cols] for i in xrange(0, n_rows * n_cols, n_cols)]
Uri Hoenig
  • 138
  • 6