用户在python中输入n*n矩阵

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32466311/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 11:38:09  来源:igfitidea点击:

taking n*n matrix input by user in python

pythonmatrixinputsplitnested-loops

提问by Shivansh Shrivastava

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

我开始用python编写代码。当我从用户那里获取两个输入并且两个输入之间有一个空格时,我的代码就像

 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

效果很好。在另一个这样的问题中,我将一个 * n 矩阵作为用户输入,我声明为arr=[[0 for i in range(n)] for j in range(n)]打印 arr 给出了一个很好的矩阵(尽管在单行中)但我要用用户输入替换每个元素“0”,所以我使用嵌套循环为

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.

这也很好用,但在每个元素后按“输入”按钮。在这个特定问题中,用户将在空格处输入一行中的元素,而不是按“输入”按钮。我想知道在这种情况下如何像上面的第一种情况一样使用 split,记住矩阵是 n*n,我们不知道什么是 n。我更喜欢避免使用 numpy 作为 Python 的初学者。

回答by Reut Sharabani

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']]
>>> 

回答by Sait

>>> 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]]

回答by knowledge

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:

好吧,如果矩阵是 n*n,这意味着您知道第一个输入行的输入行数(不,不可能input()不以按下 Enter 键结束)。所以你需要这样的东西:

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).

我使用range(len(arr[0]) - 1)所以它输入其余的行(因为矩阵宽度和高度相同并且第一行已经从输入中读取)。

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

我也.split()没有使用" "作为参数,因为它是默认参数。

回答by Pratik Vyas

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)

回答by PKBEST

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

回答by Awaldeep Singh

#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)  

回答by D.sai vamshi

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;

回答by Suraj Verma

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()

回答by Mahesh Kumar

n= 10 # n is the order of the matrix

n= 10 # n 是矩阵的阶数

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

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

print(matrix)

打印(矩阵)

回答by Sanjay Rai

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()