我在解析两个变量之间包含的矩阵时遇到了困难。这是一个我试图提取到一个numpy数组的矩阵的例子:
</MO Number>
4.224609607748e+00 4.085857782359e+00 1.273383604708e+00 -6.802974691818e-03
9.099528133406e-03 6.867550219273e-03 5.859231188647e-03 3.684441849425e-03
5.836775773317e-04 -2.316776085880e-16 -1.456850991492e-16 -2.307897076406e-17
4.140895678156e-03 2.603906355541e-03 4.125025757803e-04 -1.739011495381e-03
-1.681896173898e-03 -5.241735641835e-04 -1.739011375813e-03 -1.681896058258e-03
-5.241735281434e-04
<MO Number>
这是我写的代码:
def function3(start, end):
lines = f.readlines()
config_found = False
var = []
for line in lines:
if line.strip() == end:
config_found = False
elif config_found:
i = line.rstrip()
var.append(i)
elif line.strip() == start:
config_found = True
var1 = [elem.strip() for elem in var]
var2 = var1[1:-1]
return var2
with open(filename, 'r') as f:
mo1=np.array(function3(m['start1'],m['end1']))
其中start1和end1变量表示标头。 但是,这将返回以下内容:
array([ '4.224609607748e+00 4.085857782359e+00 1.273383604708e+00 -6.802974691818e-03',
'9.099528133406e-03 6.867550219273e-03 5.859231188647e-03 3.684441849425e-03',
'5.836775773317e-04 -2.316776085880e-16 -1.456850991492e-16 -2.307897076406e-17',
'4.140895678156e-03 2.603906355541e-03 4.125025757803e-04 -1.739011495381e-03',
'-1.681896173898e-03 -5.241735641835e-04 -1.739011375813e-03 -1.681896058258e-03',
'-5.241735281434e-04'])
似乎我的代码将矩阵的每一行存储为单个元素,当我真的希望它将每个浮点数存储为单个元素时,用逗号分隔。所以,像这样:
[ '4.224609607748e+00', '4.085857782359e+00', '1.273383604708e+00' '-6.802974691818e-03',
'9.099528133406e-03', '6.867550219273e-03', '5.859231188647e-03' '3.684441849425e-03',
等。 任何帮助将非常感谢我如何修改我的代码,甚至是一个完全不同的方法来解决这个问题。
谢谢!