简体   繁体   中英

Read a matrix from a .txt file

How would I go about reading a file like:

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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