3

I would like to know a short method to input the elements of a 2D matrix one by one. (Using only default python modules)

My current code:

i= []
for x in range(3):
    i.append(map(int, raw_input("enter the element").split()))
    for y in range(3):
        i.append(map(int, raw_input("enter the element").split()))
print i

I want the result to be like :

[[1,2,3],
 [4,5,6],
 [7,8,9]]

But end up getting:

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

I have already checked for potential duplicates, but could not find any that would take each and every element of the matrix.

Any short method would be appreciated.

EDIT: The rows and columns should be changeable separately. So, if we enter 3 rows and 4 columns, the elements should be automatically placed into their respective locations.

Example: For a 2x2 matrix

If the input is: 1,2,1,2

Then the matrix should be :

[[1,2],
 [1,2]]
Georgy
  • 12,464
  • 7
  • 65
  • 73
adb16x
  • 658
  • 6
  • 24
  • Possible duplicate of [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 09:20

3 Answers3

4

or this:

UPDATE: changed to the format i guessed you'd want :)

rows = 3
cols = 3
result = [[int(raw_input("row: %d col: %d  => " % (row, col))) 
           for col in xrange(cols)] for row in xrange(rows)]
Taxellool
  • 4,063
  • 4
  • 21
  • 38
3

Verbose, but works:

M = []
for i in range(rows):
    row = []
    M.append(row)
    for j in range(rows):
        x = raw_input("Number for element ({}, {}): ".format(i, j))
        row.append(int(x))

If you are working on matrices, you should also give NumPy a look. Then you could have done it as:

import numpy as np
M = np.array((rows, cols))
for i in range(rows):
    for j in range(cols):
         M[i, j] = int(raw_input("Number: "))
Hannes Ovrén
  • 21,229
  • 9
  • 65
  • 75
1

Try this

i= []
for x in range(3):
    i.append([int(j) for j in raw_input("enter the element").split()])

print i
ziddarth
  • 1,796
  • 1
  • 14
  • 14
  • Please check edit. Your program has equal columns and rows, moreover your result comes to be : [[1], [2], [3]] – adb16x Feb 10 '15 at 09:28