用户给了MXN矩阵,我想转换为numpy矩阵



Input

2 3 **Here 2,3 are size of mateix m,n**
2 3 4
5 6 7

输出

[
[2 3 4]
[5 6 7]
]

注意:-使用Numpy软件包

如果输入矩阵在文件中,则可以使用以下程序:

import numpy as np
x = np.loadtxt('file.txt', dtype=int, delimiter=' ') # you don't need to give the matrix size at the beginning of the file
print(x)
rows = int(input('give number of rows: '))
cols = int(input('give number of columns: '))
x = np.zeros((rows,cols), dtype=int)
for i in range(rows):
for j in range(cols):
x[i,j] = int(input(f"give matrix element for row {i} and column {j}: "))

print(x)

如果您希望用户输入矩阵元素,请使用程序的第二部分。

读取m x n输入作为 numpy 矩阵:

import numpy as np
m,n = map(int, input().split())
arr = np.zeros((m,n))
for i in range(m):
arr[i] = np.array(list(map(int, input().split())))

输出:

array([[1., 2., 3.],
[4., 5., 6.]])

最新更新