从文本文件中读取矩阵并将其存储在数组中
Reading matrix from a text file and storing it in an array
定义
我将以下矩阵存储在文本文件中:
1 0 0 1 0 1 1
0 1 0 1 1 1 0
0 0 1 0 1 1 1
我想从文本图块中读取这个矩阵并使用 python 2.7 将其存储在二维数组中。
我尝试的代码
我尝试的代码如下:
f = open('Matrix.txt')
triplets=f.read().split()
for i in range(0,len(triplets)): triplets[i]=triplets[i].split(',')
A = np.array(triplets, dtype=np.uint8)
print(A)
问题
就目前而言,上面的代码是以一维方式打印矩阵。是否可以按照上面矩阵中定义的二维方式保存矩阵?
使用np.loadtxt
:
A = np.loadtxt('filename.txt')
>>> A
array([[ 1., 0., 0., 1., 0., 1., 1.],
[ 0., 1., 0., 1., 1., 1., 0.],
[ 0., 0., 1., 0., 1., 1., 1.]])
或者,您可以像您正在做的那样逐行阅读它(但这效率不高):
A = []
with open('filename.txt', 'r') as f:
for line in f:
A.append(list(map(int,line.split())))
>>> np.array(A)
array([[1, 0, 0, 1, 0, 1, 1],
[0, 1, 0, 1, 1, 1, 0],
[0, 0, 1, 0, 1, 1, 1]])
定义
我将以下矩阵存储在文本文件中:
1 0 0 1 0 1 1
0 1 0 1 1 1 0
0 0 1 0 1 1 1
我想从文本图块中读取这个矩阵并使用 python 2.7 将其存储在二维数组中。
我尝试的代码
我尝试的代码如下:
f = open('Matrix.txt')
triplets=f.read().split()
for i in range(0,len(triplets)): triplets[i]=triplets[i].split(',')
A = np.array(triplets, dtype=np.uint8)
print(A)
问题
就目前而言,上面的代码是以一维方式打印矩阵。是否可以按照上面矩阵中定义的二维方式保存矩阵?
使用np.loadtxt
:
A = np.loadtxt('filename.txt')
>>> A
array([[ 1., 0., 0., 1., 0., 1., 1.],
[ 0., 1., 0., 1., 1., 1., 0.],
[ 0., 0., 1., 0., 1., 1., 1.]])
或者,您可以像您正在做的那样逐行阅读它(但这效率不高):
A = []
with open('filename.txt', 'r') as f:
for line in f:
A.append(list(map(int,line.split())))
>>> np.array(A)
array([[1, 0, 0, 1, 0, 1, 1],
[0, 1, 0, 1, 1, 1, 0],
[0, 0, 1, 0, 1, 1, 1]])