如何从Python中的单个输入文件中读取两个矩阵

时间:2018-05-27 17:42:28

标签: python io

我在一个.txt文件中保存了两个矩阵A和B,如下所示。

矩阵A:

2,4,5-

4,7,3

矩阵B:

1,2

5,9

1,6

在Python中,如何从该输入文件中分别读取两个矩阵A和B.

1 个答案:

答案 0 :(得分:0)

假设您的输入文件看起来像这样(矩阵用空行分隔):

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]]