0

I am trying to get a 3d list of RGB values located as text in a file and convert it to a normal list that I can use in Python.

The list on the file looks like this [[[1,0,0],[2,1,0]],[[0,1,0.5],[2,3,1.8]]].

What should I do to retrieve this list as as is, in order to use it in my code?

I tried to use functions such as split(), but I still cannot get the original list on the file because of the brackets.

Rahul Agarwal
  • 4,034
  • 7
  • 27
  • 51

4 Answers4

1

Use JSON

import json
json.loads("[[[1,0,0],[2,1,0]],[[0,1,0.5],[2,3,1.8]]]")

gives you:

[[[1, 0, 0], [2, 1, 0]], [[0, 1, 0.5], [2, 3, 1.8]]]
Florian H
  • 3,052
  • 2
  • 14
  • 25
1

You can parse it as JSON.

In [1]: s = "[[[1,0,0],[2,1,0]],[[0,1,0.5],[2,3,1.8]]]"                                                                                                                                                                                                       

In [2]: import json                                                                                                                                                                                                                                           

In [3]: json.loads(s)                                                                                                                                                                                                                                         
Out[3]: [[[1, 0, 0], [2, 1, 0]], [[0, 1, 0.5], [2, 3, 1.8]]]

If you want to read it from a file:

import json

f = open("file_path", "r")
your_list = json.load(f)
AdamGold
  • 4,941
  • 4
  • 29
  • 47
1

You can use ast.literal_eval in this case (doc):

from ast import literal_eval

txt = '[[[1,0,0],[2,1,0]],[[0,1,0.5],[2,3,1.8]]]'

l = literal_eval(txt)

print(l)

Prints:

[[[1, 0, 0], [2, 1, 0]], [[0, 1, 0.5], [2, 3, 1.8]]]
Andrej Kesely
  • 168,389
  • 15
  • 48
  • 91
1

You might want to use the ast library:

import ast

ast.literal_eval("[[[1,0,0],[2,1,0]],[[0,1,0.5],[2,3,1.8]]]")

# [[[1, 0, 0], [2, 1, 0]], [[0, 1, 0.5], [2, 3, 1.8]]]

The benefit here being literal_eval will safely parse strings into python objects, and is not limited to json-specific syntax as the json module is

C.Nivs
  • 12,353
  • 2
  • 19
  • 44