Domanda

I have a .txt file that looks like:

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

And I want to transform the colums into lists of floats like this: L1=[846160, 820434, 849103, 846353, 848613] etc.

The code I tried so far is:

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

But when I try to do this it gives me the following error:

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

Any ideas on what I'm doing wrong or how I could improve this code?

È stato utile?

Soluzione

To get all of your columns:

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

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

The value of l is now

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

And now to floats

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

l is now

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

Altri suggerimenti

with open("test.txt") as inf:
    L1 = [float(line.split()[0]) for line in inf]
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top