How can I read in my file line by line with each line as a list of floats?

前端 未结 2 692
萌比男神i
萌比男神i 2021-01-29 05:56

I have a file where each line has a pair of coordinates like so:

[-74.0104294, 40.6996416]

The code that I\'m using to read them in is:

2条回答
  •  面向向阳花
    2021-01-29 06:11

    even better way than @ZeroPiraeus solution use ast.literal_eval which can evaluate any literal of python (here a list literal compound of float literal)

    import ast
    m_verts = []
    with open('Manhattan_Coords.txt') as f:
        for line in f:
            pair = ast.literal_eval(line)
            m_verts.append(pair)
    

    but for construction of the list even better is list comprehension

    import ast
    with open('Manhattan_Coords.txt') as f:
        m_verts = [ast.literal_eval(line) for line in f]
    

提交回复
热议问题