0
matrix = []
n = int(input("n: "))
m = int(input("m: "))

for i in range(m):
  data = input()
  data_list = data.split()
  data_list = [int(i) for i in data_list]

  matrix.append(data_list)

I made a python code for put an integer in MxN array. I want to change it into Nx(M+1) array

change array[m][n] into array[n][m]

and put 0 int the array[][m+1]

for example:

n : 4
m : 3

Input integers:

1 2 3 4
5 6 7 8
9 10 11 12

Turns into:

1 5 9 0
2 6 10 0
3 7 11 0
4 8 12 0

how can I make that code to do this thing? I tried

for i in range(m):
  for j in range(n):
     matrix[i][j] = matrix[j][i]

but this is wrong way to do it.

Arslanbekov Denis
  • 1,674
  • 12
  • 26
JLee
  • 13
  • 1
  • 3
  • Can you clarify whether your input and output should be 2-dimensional (a list of lists, i.e. `matrix[m][n]`) or 1-dimensional (a single list of `m*n` items)? – vthorsteinsson Oct 19 '18 at 16:53

2 Answers2

0
matrix = [
  [ 1, 2, 3, 4 ],
  [ 5, 6, 7, 8 ],
  [ 9, 10, 11, 12 ]
]

def change(matrix):
    m = len(matrix)
    n = len(matrix[0])
    result = [[] for i in range(n)]
    for i in range(m+1):
        for j in range(n):
            if i == m:
                result[j].append(0)
            else:
                result[j].append(matrix[i][j])
    return result

changed = change(matrix)
print(changed)
wang
  • 1,660
  • 9
  • 20
0

To solve your problem, get acquainted with NumPy.

import numpy as np
t1 = np.arange(1, 13).reshape(3, 4)

creates your source table:

array([[ 1,  2,  3,  4],
       [ 5,  6,  7,  8],
       [ 9, 10, 11, 12]])

Then you should transpose it:

t2 = t1.T

which gives:

array([[ 1,  5,  9],
       [ 2,  6, 10],
       [ 3,  7, 11],
       [ 4,  8, 12]])

And finally:

np.c_[ t2, np.zeros(4) ]

adds a column of 4 zeroes, giving the final result:

array([[ 1.,  5.,  9.,  0.],
       [ 2.,  6., 10.,  0.],
       [ 3.,  7., 11.,  0.],
       [ 4.,  8., 12.,  0.]])
Valdi_Bo
  • 30,023
  • 4
  • 23
  • 41