Search code examples
pythondictionarypython-itertools

python load data from file in one line


I have some data in a file like that :

18499 0.00822792
14606 0.00778273
3926 0.00287178
2013 0.00130196
3053 0.000829384
16320 0.00249749

I would like to load and parse data in python in one line, this what I wrote for the moment:

with open(input_file) as f:
    data = f.read()
data = [line.split() for line in data.split('\n') if line]
x = list(map((lambda x:float(x[0])), data))
y = list(map((lambda x:float(x[1])), data))

So the goal is to have something like:

x, y = ....

Solution

  • with open(input_file) as f:
        x,y = zip(*[map(float,line.split()) for line in f])
    print x
    print y
    

    I think I got my parentheses balanced there ... but just cause you can doesnt mean you should ...

    [edit] fixed the code to actually work...