bob
bob

Reputation: 75

Convert a list of 3D coordinates in string format to a list of floats

I have a list of 3D coordinates in the format as list_X.

list_X =' [43.807  7.064 77.155], [35.099  3.179 82.838], [53.176052  -5.4618497 83.53082  ], [39.75858    1.5679997 74.76174  ], [42.055664  2.459083 80.89183 ]'

I want to convert into floats as below

list_X =[43.807  7.064 77.155], [35.099  3.179 82.838], [53.176052  -5.4618497 83.53082  ], [39.75858    1.5679997 74.76174  ], [42.055664  2.459083 80.89183 ]

I was trying as below which doesn't work

list1=[float(x) for x in list_X]

Upvotes: 0

Views: 41

Answers (1)

HerrAlvé
HerrAlvé

Reputation: 645

You can clean up the string to fit in the format of a list (i.e., add surrounding square brackets ([]) to contain all of the 3D coordinates, and separate the values by commas), and then use the json.loads method.

import json

list_X ='[[43.807, 7.064, 77.155], [35.099, 3.179, 82.838], [53.176052, -5.4618497, 83.53082], [39.75858, 1.5679997, 74.76174], [42.055664, 2.459083, 80.89183]]'

print(json.loads(list_X))

# Output

[[43.807, 7.064, 77.155], [35.099, 3.179, 82.838], [53.176052, -5.4618497, 83.53082], [39.75858, 1.5679997, 74.76174], [42.055664, 2.459083, 80.89183]]

Upvotes: 1

Related Questions