【发布时间】:2018-05-27 17:42:27
【问题描述】:
我已将两个矩阵 A 和 B 保存在一个 .txt 文件中,如下所示。
矩阵 A:
2,4,5
4,7,3
矩阵 B:
1,2
5,9
1,6
在 Python 中,如何从这个输入文件中分别读取两个矩阵 A 和 B。
【问题讨论】:
我已将两个矩阵 A 和 B 保存在一个 .txt 文件中,如下所示。
矩阵 A:
2,4,5
4,7,3
矩阵 B:
1,2
5,9
1,6
在 Python 中,如何从这个输入文件中分别读取两个矩阵 A 和 B。
【问题讨论】:
假设您的输入文件看起来像这样(矩阵由空行分隔):
2,4,5
4,7,3
1,2
5,9
1,6
这个python代码(用于python3):
input_file = open('input.txt', 'r')
a = []
b = []
current = a # Current will point to the current matrix
for line in input_file.readlines():
if ',' not in line: # This is our separator - a line with no ',', switch a matrix
current = b
else:
current.append([]) # Add a row to our current matrix
for x in line.split(','): # Values are separated by ','
current[len(current) - 1].append(int(x)) # Add int(x) to the last line
print(a, b)
input_file.close()
输出以下内容:
[[2, 4, 5], [4, 7, 3]] [[1, 2], [5, 9], [1, 6]]
【讨论】: