1

I have this string:

[0, 0], [1, 7], [2, 1], [3, 1], [4, 4], [5, 3], [6, 0], [7, 0], [8, 0], [9,0],
[10, 0], [11, 0], [12, 0], [13, 0], [14, 0], [15, 0], [16, 0], [17, 0], 
[18,0], [19, 0], [20, 0], [21, 0], [22, 0], [23, 0], [24, 0], [25, 0], 
[26, 0], [27, 0], [28, 0], [29, 0], [30, 0]

and I need to convert it in a 2D list

Can you help me?, I have tried with string.split(), but I can't find the correct combination.

Thanks a lot.

linusg
  • 6,289
  • 4
  • 28
  • 78
Madmartigan
  • 453
  • 1
  • 5
  • 14

1 Answers1

3

You can use literal_eval and list to do this:

import ast

s = "[0, 0], [1, 7], [2, 1], [3, 1], [4, 4], [5, 3], [6, 0], [7, 0], [8, 0], [9,0],[10, 0], [11, 0], [12, 0], [13, 0], [14, 0], [15, 0], [16, 0], [17, 0], [18,0], [19, 0], [20, 0], [21, 0], [22, 0], [23, 0], [24, 0], [25, 0], [26, 0], [27, 0], [28, 0], [29, 0], [30, 0]"

l = list(ast.literal_eval(s))

Output:

>>> l
[[0, 0], [1, 7], [2, 1], [3, 1], [4, 4], [5, 3], [6, 0], [7, 0], [8, 0], [9, 0], [10, 0], [11, 0], [12, 0], [13, 0], [14, 0], [15, 0], [16, 0], [17, 0], [18, 0], [19, 0], [20, 0], [21, 0], [22, 0], [23, 0], [24, 0], [25, 0], [26, 0], [27, 0], [28, 0], [29, 0], [30, 0]]
Farhan.K
  • 3,425
  • 2
  • 15
  • 26