0

I am trying to parse a textfile where a matrix is saved in the string format: "[[0,1],[1,0]]"

To goal is to parse the .txt file and turn it into an actual matrix represented by an arrays of arrays stored in some variable. I am new to python and programming in general and can't think of an nice way to do this.

I only need help with how to construct the python matrix from what we get in the .txt file.

user128226
  • 29
  • 5

1 Answers1

0

As commented by @Kraigolas, the python eval() function will evaluate that expression and convert it to a Python list of lists.

To elaborate further, if you want to then work with it as a matrix, your best bet is to then convert it to a NumPy array.

This can be a one liner:

import numpy as np
arr = np.array(eval("[[0,1],[1,0]]"))

You then can work with arr using NumPy as you wish.

paisanco
  • 4,098
  • 6
  • 27
  • 33