如何在python中从文本文件的列中生成浮点数?

时间:2014-04-29 20:11:47

标签: python list text floating-point

我有一个.txt文件,看起来像:

846160  0.388  0.329  0.69  0.9  0.626  0.621  0.399  0.37
820434  -0.296  -0.503  -0.454  -0.868  -0.721  -0.918  -0.486  -0.582
849103  -0.246  -0.935  -0.277  -0.175  -0.278  -0.075  -0.236  -0.417
846353  0.769  0.929  0.977  1.095  1.058  0.864  0.689  0.492
848613  -0.365  -0.76  -0.305  -0.293  -0.364  -0.155  -0.472  -0.606

我想把colums转换成这样的浮点数列表: L1=[846160, 820434, 849103, 846353, 848613]等。

我到目前为止尝试的代码是:

f=open("test.txt","r")
List=[]
List.extend(f)
List=map(lambda s: s.strip(), List)
[float(e) for e in List]

但是当我尝试这样做时,它会给我以下错误:

ValueError: invalid literal for float(): 846160  0.388  0.329  0.69  0.9  0.626  0.621  0.399  0.37

关于我做错了什么或者如何改进此代码的任何想法?

2 个答案:

答案 0 :(得分:2)

获取所有列:

with open("test.txt") as infile:
    l = [line.split() for line in infile]

l = map(list, zip(*l))

l的值现在是

[['846160', '820434', '849103', '846353', '848613'],
 ['0.388', '-0.296', '-0.246', '0.769', '-0.365'],
 ['0.329', '-0.503', '-0.935', '0.929', '-0.76'],
 ['0.69', '-0.454', '-0.277', '0.977', '-0.305'],
 ['0.9', '-0.868', '-0.175', '1.095', '-0.293'],
 ['0.626', '-0.721', '-0.278', '1.058', '-0.364'],
 ['0.621', '-0.918', '-0.075', '0.864', '-0.155'],
 ['0.399', '-0.486', '-0.236', '0.689', '-0.472'],
 ['0.37', '-0.582', '-0.417', '0.492', '-0.606']]

现在浮动

l = [map(float,i) for i in l]

l现在

[[846160.0, 820434.0, 849103.0, 846353.0, 848613.0],
[0.388, -0.296, -0.246, 0.769, -0.365],
[0.329, -0.503, -0.935, 0.929, -0.76],
[0.69, -0.454, -0.277, 0.977, -0.305],
[0.9, -0.868, -0.175, 1.095, -0.293],
[0.626, -0.721, -0.278, 1.058, -0.364],
[0.621, -0.918, -0.075, 0.864, -0.155],
[0.399, -0.486, -0.236, 0.689, -0.472],
[0.37, -0.582, -0.417, 0.492, -0.606]]

答案 1 :(得分:1)

with open("test.txt") as inf:
    L1 = [float(line.split()[0]) for line in inf]