我开始在python中编码。当我从用户那里获取两个输入时,两个输入之间有一个空格,我的代码就像
min, p = input().split(" ")
min=int(min)
p=float(p)
工作得很好。在另一个这样的问题我要采用* 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()
这也很好,但在每个元素后按下“输入”按钮。在这个特定问题中,用户将在空格中输入一行中的元素,而不是按下“输入”按钮。我想知道如何在这种情况下使用split,就像上面的第一种情况一样,请记住矩阵是n * n,我们不知道n是什么。我宁愿避免使用numpy作为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)
你可以这样做:
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())))
现在您在控制台中输入如下值:
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
您可以尝试这种简单的方法(在每个数字后按Enter键......工作正常)::
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)
尝试这样的事情,而不是使用现有的列表逐个设置矩阵:
# 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)]
例:
>>> 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']]
>>>
>>> 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]]
好吧,如果矩阵是n * n,这意味着第一个输入行你知道输入行的数量(并且没有,input()
不能以键输入结束按下)。所以你需要这样的东西:
arr = []
arr.append(input().split())
for x in range(len(arr[0]) - 1):
arr.append(input().split())
我使用了range(len(arr[0]) - 1)
,因此它输入了其余的行(因为矩阵宽度和高度相同,并且已经从输入读取了第一行)。
我还使用没有.split()
的" "
作为参数,因为它是默认参数。
试试下面,
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;