Andreas Bengtsson
Andreas Bengtsson

Reputation: 43

Parse list of numbers into list in python

I have a text file containing numbers in the following format:

 {5.2, 7.3}
 {1.4, 6.2}

I would like to load these into a list of floats with two columns and the same number of rows as entries in the file, like this [[5.2, 7.3], [1.4, 6.2], ...]

Currently I'm doing this:

f = open(filename,'r')

mylist = []


for line in f:

    strippedLine = line.strip('{}\n')
    splitLine = strippedLine.split(',')
    a=float(splitLine[0])
    b=float(splitLine[1])
    ab=np.array([a,b])
    mylist.append(ab)


f.close()

This works fine, but I would like to get rid of the for-loop, i.e. only use split, strip and float. Something like this:

f = open(filename,'r')
lines = f.read()
f.close

split_lines = lines.split('\n')
# Then something more here to get rid of { and }, and to rearrange into the shape I want

Could I maybe replace { and } with [ and ], and then try to convert it into a list?

Upvotes: 2

Views: 1133

Answers (2)

Burhan Khalid
Burhan Khalid

Reputation: 174624

How about another approach, that doesn't use replacement and evaluation (something risky), but rather uses regular expressions. It does violate your "no for loop" rule though:

>>> import re
>>> [[float(i) for i in re.findall(r'(\d\.?\d?)', z)] for z in open('foo.txt').readlines() if len(z.strip())]
[[5.2, 7.3], [1.4, 6.2]]

Upvotes: 2

Duncan
Duncan

Reputation: 95662

You can do some simple string replacements and then use ast.literal_eval:

>>> data = "{5.2, 7.3}\n{1.4, 6.2}\n"
>>> import ast
>>> ast.literal_eval(data.replace('{','[').replace('}',']').replace('\n',','))
([5.2, 7.3], [1.4, 6.2])
>>> 

Alternatively use str.join on the file to get the commas in the right place:

with open('somefile.txt') as f:
    data = ','.join(line.replace('{','[').replace('}',']')
        for line in f if line.strip())
    return ast.literal_eval(data)

Upvotes: 4

Related Questions