2

I have a String that is formatted like a 2D array like this:

"[[1, 0, 0, 0], [1, 0, 0, 0], [1, 0, 0, 0], [1, 0, 0, 0]]"

How can I get the program to read the string as an actual 2D array like this

[[1, 0, 0, 0], [1, 0, 0, 0], [1, 0, 0, 0], [1, 0, 0, 0]]

so that I can perform matrix calculations?

I've tried removing the commas and brackets and then converting the string numbers to integer numbers but that does not work because I need to keep the shape of the 2D array. In this example, I would need the final 2D array to be size [4][4].

Vishal Singh
  • 5,236
  • 2
  • 15
  • 27
whiplash
  • 23
  • 3

2 Answers2

3

Given that the 2D list string happens to be valid syntax for a Python 2D list, you could just use the eval() function:

output = eval("[[1, 0, 0, 0], [1, 0, 0, 0], [1, 0, 0, 0], [1, 0, 0, 0]]")
print(output)
print(output[0])

This prints:

[[1, 0, 0, 0], [1, 0, 0, 0], [1, 0, 0, 0], [1, 0, 0, 0]]
[1, 0, 0, 0]
Tim Biegeleisen
  • 387,723
  • 20
  • 200
  • 263
2
In [4]: import ast                                                                                                                                                              

In [5]: array = "[[1, 0, 0, 0], [1, 0, 0, 0], [1, 0, 0, 0], [1, 0, 0, 0]]"                                                                                                      

In [6]: array = ast.literal_eval(array)                                                                                                                                         

In [7]: array                                                                                                                                                                   
Out[7]: [[1, 0, 0, 0], [1, 0, 0, 0], [1, 0, 0, 0], [1, 0, 0, 0]]

ast.literal_eval(node_or_string)[Python-doc]Safely evaluate an expression node or a string containing the following Python literal :: strings, bytes, numbers, tuples, lists, dicts, sets, booleans, and None.

Vishal Singh
  • 5,236
  • 2
  • 15
  • 27