取 'n' space 分隔的整数在 Python 中,存储在矩阵中并打印矩阵
Taking 'n' space separated integers in Python, storing in matrix and print the matrix
我想取 n
space 分隔的整数并存储在矩阵中,然后打印矩阵。
我正在使用 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
如果我尝试使用 space 分隔的整数,然后按 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()
我想取 n
space 分隔的整数并存储在矩阵中,然后打印矩阵。
我正在使用 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
如果我尝试使用 space 分隔的整数,然后按 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()