【发布时间】:2020-12-30 23:29:23
【问题描述】:
我是 python 新手,正在尝试熟悉它的库功能
假设我有一个文件名 case_test.txt,其内容如下:
cases: 2
matrix size: 5 x 5
case #1 matrix:
x. v. t. u. w.
x 0.5 0.6 1.2 2.0 1.3
v 0.7 0.8 1.0 3.0 0.3
t 0.4 0.3 0.7 0.1 0.6
u 1.2 3.2 0.2 2.9 1.9
w 0.2 0.5 0.9 0.3 1.7
case #2 matrix:
x. v. t. u. w.
x 1.8 0.9 0.0 1.3 1.4
v 0.5 0.5 2.3 3.3 0.1
t 1.3 0.3 0.7 0.1 0.2
u 1.7 3.9 2.5 1.2 1.3
w 0.1 0.2 0.9 0.3 1.1
variables: 5
到目前为止,我有以下内容:
def read_file(text_File):
file = open(text_File, "r") #open file for reading
stuff = [] #empty list to hold contents after "case #1 matrix"
for line in file:
#For in is used to loop through lines in a file
if 'case #1 matrix:' in line:
print("At matrix one\n")
##Reached matrix one
stuff.append = ([list(line) for contents in line.split()])
if 'case #2 matrix:' in line:
print("At matrix two\n")
##Breaks when the next matrix is encountered
break
print(stuff)
print("Contents in list stuff printed")
return stuff
最后,我想从列表“stuff”中提取矩阵,然后将其作为浮点值存储在单独的列表中。有关如何解决此问题的任何提示都会有所帮助。谢谢!
【问题讨论】:
-
case #2 存在缩进错误,您编写它的方式仅在该行已包含 case #1 时才会执行,而且您仅有效地将带有 case #1 的行附加到填充并忽略所有其他行