Search code examples
pythonlistsplitstrip

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?


Solution

  • 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)