在Python中取"n"个空格分隔的整数,存储在矩阵中并打印矩阵



我想取n空间分隔的整数并存储在矩阵中,然后打印矩阵。我正在使用Python 3.7.

我的代码是:


size = int(input("nEnter number of rows or colums: ")) #square matrix
#Define the matrix
matrix = []
print("nEnter the entries:")
#for user input
for row in range(size):     
temp = []
for column in range(size):      
temp.append(int(input()))
matrix.append(temp)

#To print the matrix
print("nThe matrix is :")
for i in range(size):
for j in range(size):
print(matrix[i][j], end="t")
print()

我只能接受像这样的输入

Enter number of rows or colums: 2
Enter the entries:
1
2
3
4
The matrix is :
1       2
3       4

但我想像这个一样输入

Enter number of rows or colums: 2
Enter the entries:
1 2
3 4
The matrix is :
1       2
3       4

如果我尝试使用空格分隔的整数,然后按Enter键输入新行,我会得到下面的错误消息

Enter number of rows or colums: 2
Enter the entries:
1 2
Traceback (most recent call last):
File "e:/Python/matrix.py", line 12, in <module>
temp.append(int(input()))
ValueError: invalid literal for int() with base 10: '1 2'

有人能帮我吗?提前谢谢。

以下是更新后的代码:

size = int(input("nEnter number of rows or colums: ")) #square matrix
#Define the matrix
matrix = []
print("nEnter the entries:")
#for user input
for row in range(size):
# Read row, space separated value
matrix.append(
[int(n) for n in input().split(' ')]
)
#To print the matrix
print("nThe matrix is :")
for i in range(size):
for j in range(size):
print(matrix[i][j], end="t")
print()

相关内容

  • 没有找到相关文章

最新更新