在Python中接受用户输入的n * n矩阵 [英] taking n*n matrix input by user in python

查看:2987
本文介绍了在Python中接受用户输入的n * n矩阵的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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)

效果很好.在另一个这样的问题中,我将n * n矩阵作为我声明为arr=[[0 for i in range(n)] for j in range(n)]的用户输入 打印arr可以得到一个很好的矩阵(虽然在单行中),但是我要用用户输入替换每个元素'0',所以我将嵌套循环用作

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

这也很好用,但是在每个元素后面按"enter"(输入)按钮.在此特定问题中,用户将在空间中按行输入元素,而不是按输入"按钮.我想知道如何在这种情况下使用拆分,就像上面的第一种情况一样,请记住矩阵是n * n,而我们不知道n是什么.我更喜欢避免将numpy用作python的初学者.

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.

推荐答案

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

这篇关于在Python中接受用户输入的n * n矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆