0

Hello I am looking to get a string that looks like this : string: "[[[[1.0], 1.0], [[1.0], 1.0]], [[[1.0, 1.0], 1.0], [[1.0, 1.0], 1.0]]]" To an actual list: list: [[[[1.0], 1.0], [[1.0], 1.0]], [[[1.0, 1.0], 1.0], [[1.0, 1.0], 1.0]]

My code reads from an file which stores a flat out str(list) and I want to retrieve it from the file as a list not a str. If you have a better way of storing and retrieving it would help a lot.

R0Best
  • 41
  • 6
  • 1
    "My code reads from an file which stores a flat out str(list)" **don't do that**. Don't just dump the `str` representation of an object into a file ... use an *actual serialization format*, like `JSON` or `pickle` or heck, in this case, even csv. – juanpa.arrivillaga Nov 24 '21 at 19:39

2 Answers2

1

Just use json library

import json
l = json.loads("[[[[1.0], 1.0], [[1.0], 1.0]], [[[1.0, 1.0], 1.0], [[1.0, 1.0], 1.0]]]")
mama
  • 2,046
  • 1
  • 7
  • 24
1
string = "[[[[1.0], 1.0], [[1.0], 1.0]], [[[1.0, 1.0], 1.0], [[1.0, 1.0], 1.0]]]"
print(string)
print(type(string))

new = eval(string)
print(new)
print(type(new))

Output:

[[[[1.0], 1.0], [[1.0], 1.0]], [[[1.0, 1.0], 1.0], [[1.0, 1.0], 1.0]]]
<class 'str'>
[[[[1.0], 1.0], [[1.0], 1.0]], [[[1.0, 1.0], 1.0], [[1.0, 1.0], 1.0]]]
<class 'list'>

Not sure if safe, but I used eval(string), which converted it to the list

knmarcin
  • 29
  • 1