简体   繁体   English

从 a.txt 文件中读取矩阵

[英]Read a matrix from a .txt file

How would I go about reading a file like:我将如何 go 关于读取如下文件:

4
1.66 3.79 2.65 4.25
4.46 1.46 8.51 3.14
3.51 1.44 8.26 7.87
0.40 3.31 1.97 2.30
1.54 2.84 9.07 8.44

Where the first number is the number of equations in the system of equations, and the final row is the what the corresponding equations equal.其中第一个数字是方程组中方程的数量,最后一行是相应方程相等的数。 For example, this would be:例如,这将是:

1.66 3.79 2.65 4.25 | 1.54
4.46 1.46 8.51 3.14 | 2.84
3.51 1.44 8.26 7.87 | 9.07
0.40 3.31 1.97 2.30 | 8.44

as a matrix.作为矩阵。 My question is in python, how do I go about translating that into something like this:我的问题是在 python 中,我如何将 go 翻译成这样的:

A = [[1.66, 3.79, 2.65, 4.25], [4.46, 1.46, 8.51, 3.14], [3.51, 1.44, 8.26, 7.87], [0.40, 3.31, 1.97, 2.30]]
B = [1.54, 2.84, 9.07, 8.44]
In [7]: a = []

In [8]: b = []

In [9]: with open("a.txt") as f:
   ...:     data = f.readlines()
   ...:     no_of_equations = int(data[0].strip())
   ...:     for i in data[1:no_of_equations+1]:
   ...:         a.append(list(map(float,i.split())))
   ...:     b.append(list(map(float, data[no_of_equations+1].split())))
   ...:

In [10]: a
Out[10]:
[[1.66, 3.79, 2.65, 4.25],
 [4.46, 1.46, 8.51, 3.14],
 [3.51, 1.44, 8.26, 7.87],
 [0.4, 3.31, 1.97, 2.3]]

In [11]: b
Out[11]: [[1.54, 2.84, 9.07, 8.44]]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM