taking n*n matrix input by user in python

2020-06-29 02:17发布

问题:

I am starting to code in python. When I was to take two inputs from user with a space between the two inputs my code was like

 min, p = input().split(" ")  
min=int(min)
p=float(p)

which worked fine. In another such problem I am to take a n*n matrix as user input which I declared as arr=[[0 for i in range(n)] for j in range(n)] printing the arr gives a fine matrix(in a single row though) but I am to replace each element '0'with a user input so I use nested loops as

for i in range(0,n)
    for j in range(0,n)
       arr[i][j]=input()

this also worked fine but with a press of 'enter' button after each element. In this particular problem the user will input elements in one row at space instead of pressing 'enter' button. I wanted to know how to use split in this case like in first case above, keeping in mind the matrix is n*n where we don't know what is n. I prefer to avoid using numpy being a beginner with python.

回答1:

You can do this:

rows = int(input("Enter number of rows in the matrix: "))
columns = int(input("Enter number of columns in the matrix: "))
matrix = []
print("Enter the %s x %s matrix: "% (rows, columns))
for i in range(rows):
    matrix.append(list(map(int, input().rstrip().split())))

Now you input in the console values like this:

Enter number of rows in the matrix: 2
Enter number of columns in the matrix: 2
Enter the 2 x 2 matrix:
1 2
3 4


回答2:

#Take matrix size as input
n=int(input("Enter the matrix size"))

import numpy as np

#initialise nxn matrix with zeroes
mat=np.zeros((n,n))

#input each row at a time,with each element separated by a space
for i in range(n):
   mat[i]=input().split(" ")
print(mat)  


回答3:

You can try this simple approach (press enter after each digit...works fine)::

m1=[[0,0,0],[0,0,0],[0,0,0]]
for x in range (0,3):
    for y in range (0,3):
        m1[x][y]=input()
print (m1)


回答4:

Try something like this instead of setting the matrix one by one using existing list(s):

# take input from user in one row
nn_matrix = raw_input().split()
total_cells =  len(nn_matrix)
# calculate 'n'
row_cells = int(total_cells**0.5)
# calculate rows
matrix = [nn_matrix[i:i+row_cells] for i in xrange(0, total_cells, row_cells)]

Example:

>>> nn_matrix = raw_input().split()
1 2 3 4 5 6 7 8 9
>>> total_cells =  len(nn_matrix)
>>> row_cells = int(total_cells**0.5)
>>> matrix = [nn_matrix[i:i+row_cells] for i in xrange(0, total_cells, row_cells)]
>>> matrix
[['1', '2', '3'], ['4', '5', '6'], ['7', '8', '9']]
>>> 


回答5:

>>> import math
>>> line = ' '.join(map(str, range(4*4))) # Take input from user
'0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15'
>>> items = map(int, line.split()) # convert str to int
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
>>> n = int(math.sqrt(len(items))) # len(items) should be n**2
4
>>> matrix = [ items[i*n:(i+1)*n] for i in range(n) ]
[[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11], [12, 13, 14, 15]]


回答6:

Well if matrix is n*n that means with first input line you know number of input lines (and no, it's impossible for input() to not end with key enter is pressed). So you need something like this:

arr = []
arr.append(input().split())
for x in range(len(arr[0]) - 1):
    arr.append(input().split())

I used range(len(arr[0]) - 1) so it inputs rest of lines (because matrix width and height is same and one first line is already read from input).

Also I used .split() without " " as parameter because it's default parameter.



回答7:

Try with below,

r=int(input("enter number of rows"));
c=int(input("enter number of columns"));
mat=[];
for row in range(r):
    a=[]
    for col in range(c):
        a.append(row*col);
    mat.append(a)

print mat;


回答8:

print("Enter The row and column :")
row,col=map(int,input().split())
matrix = [] 
print("Enter the entries rowwise:") 

# For user input 
for i in range(row):          # for loop for row entries 
a =[] 
for j in range(col):      #  for loop for column entries 
     a.append(int(input())) 
matrix.append(a) 
for i in range(row): 
   for j in range(col): 
      print(matrix[i][j], end = " ") 
print()


回答9:

n= 10 # n is the order of the matrix

matrix = [[int(j) for j in input().split()] for i in range(n)]

print(matrix)



回答10:

r = int(input("Enret Number of Raws : "))

c = int(input("Enter Number of Cols : "))

a=[]

for i in range(r):

   b=[]

   for j in range(c):

      j=int(input("Enter Number in pocket ["+str(i)+"]["+str(j)+"]"))

      b.append(j)

   a.append(b)

for i in  range(r):

   for j in range(c):

      print(a[i][j],end=" ")

   print()