1

I have a list of strings in the format:

["[[xxx], [yyy]]",
 "[[xxx], [xxx], [yyy]]",
 "[[zzz]]"...

But I want it to be in a list of lists in the format:

[[[xxx], [yyy]],
 [[xxx], [xxx], [yyy]],
 [[zzz]]...

I tried ast, strip and split, etc... but can't seem to get it to work.

Edit: Editing to make more general.

lp97
  • 75
  • 7
  • 3
    Does this answer your question? [Convert string representation of list to list](https://stackoverflow.com/questions/1894269/convert-string-representation-of-list-to-list) – cwalvoort Jan 27 '20 at 14:44

2 Answers2

4

ast.literal_eval works for me using it with a list comprehension. Since you have a list of strings, you need to evaluate each one:

import ast

[ast.literal_eval(s) for s in l]

result

[[[1, 1, 'D'],
  [2, 5, 'C'],
  [6, 22, 'S'],
  [23, 57, 'C'],
  [58, 59, 'S'],...
Mark
  • 90,562
  • 7
  • 108
  • 148
0

converting list of sttrings to list of lists by using 'translate'

data = ["[[xxx], [yyy]]", "[[xxx], [xxx], [yyy]]"]
tal = {39: None}
a = str(data).translate(tal)
print(str(data).translate(tal))

result

[[[xxx], [yyy]], [[xxx], [xxx], [yyy]]]
vijju
  • 21
  • 2