1

I'm reading lists that have lost their format while conversions, so the orinial list looks now like:

my_list = '[[-0.2226099967956543, 0.2235500067472458, -0.2384900003671646, 0.14377999305725098]]'

for that I'm doing the following:

my_list = my_list.replace('[','').replace('[','').split()
type(my_list)
list

Which works, but doesn't looks very pythonic to me. Is thera better option?

Luis Ramon Ramirez Rodriguez
  • 9,591
  • 27
  • 102
  • 181

2 Answers2

2

So we have ast

my_list = '[-0.2226099967956543, 0.2235500067472458, -0.2384900003671646, 0.14377999305725098]'
import ast
ast.literal_eval(my_list)
Out[567]: 
[-0.2226099967956543,
 0.2235500067472458,
 -0.2384900003671646,
 0.14377999305725098]
BENY
  • 317,841
  • 20
  • 164
  • 234
2

Use json.loads, also, I added an extra bracket at the end of my_list since it's missing a bracket:

>>> import json
>>> my_list = '[[-0.2226099967956543, 0.2235500067472458, -0.2384900003671646, 0.14377999305725098]]'
>>> json.loads(my_list)
[[-0.2226099967956543, 0.2235500067472458, -0.2384900003671646, 0.14377999305725098]]
>>> type(json.loads(my_list))
<class 'list'>
>>> 
U13-Forward
  • 69,221
  • 14
  • 89
  • 114