Python Numpy数组从文本文件读取到2D数组

时间:2014-01-05 01:18:18

标签: python numpy

我有一个文本文件,其中包含以下内容:

-11.3815 -14.552 -15.7591 -18.5273 -14.6479 -12.7006 -13.9164 -19.8172 -22.951 -16.5832 
-16.555 -17.6044 -15.9577 -15.3363 -17.7223 -18.9881 -22.3789 -24.4881 -16.6685 -17.9475 
-18.2015 -15.2949 -15.5407 -18.8215 -24.5371 -17.0939 -15.3251 -13.1195 -13.3332 -19.3353 
-14.6149 -14.5243 -15.1842 -15.5911 -14.3217 -15.4211

内部有更多数据。我想在2D数组中读取它。我尝试过以下方法:

with open('test.txt') as file:
     array2d = [[float(digit) for digit in line.strip()] for line in file]

似乎只是得到了:

ValueError: could not convert string to float: -

知道如何解决这个问题吗?

1 个答案:

答案 0 :(得分:9)

您必须使用

split()

而不是

strip()

因为strip()返回一个字符串,所以你在迭代该字符串的每个字符。 split()返回一个列表,这就是您所需要的。阅读Python docs中的更多内容。

<强>代码:

with open('sample.txt') as file:
    array2d = [[float(digit) for digit in line.split()] for line in file]

print array2d

<强>输出:

[[-11.3815, -14.552, -15.7591, -18.5273, -14.6479, -12.7006, -13.9164, -19.8172, -22.951, -16.5832], [-16.555, -17.6044, -15.9577, -15.3363, -17.7223, -18.9881, -22.3789, -24.4881, -16.6685, -17.9475], [-18.2015, -15.2949, -15.5407, -18.8215, -24.5371, -17.0939, -15.3251, -13.1195, -13.3332, -19.3353], [-14.6149, -14.5243, -15.1842, -15.5911, -14.3217, -15.4211]]