Convert string entered into input() back to two dimensional matrix

69 Views Asked by At

In a python program I am writing in CodeSkupltor3, data is stored as a single number in a list of lists (a 2d matrix). Because CodeSkulptor can't save files, I added an option for the user to export the data. It is printed out for the user to copy to the clipboard.

Here is an example of what the matrix might look like:

[[0, 3, 4, 3, 2], [1, 2, 1, 2, 3], [3, 3, 3, 1, 2], [3, 4, 0, 3, 2], [2, 2, 2, 1, 0]]

However, the number of lists in the main list can vary, as do the number of integers in the sub-lists.

The user should be able to paste the data back into the program when prompted by an input() statement. Because all of the data passed into the input statement is in string format, it needs to be converted back into a matrix to use.

CodeSkulptor doesn't have num.py or eval(). I have tried using various combinations of string.split(), but no combination that I've tried breaks them up correctly. I also tried using list(), but the result is that each character in the string becomes an item in the list:

['[', '[', '0', ',', ' ', '3', ',', ' ', '4', ',', ' ', '3', ',', ' ', '2', ']', ',', ' ', '[', '1', ',', ' ', '2', ',', ' ', '1', ',', ' ', '2', ',', ' ', '3', ']', ',', ' ', '[', '3', ',', ' ', '3', ',', ' ', '3', ',', ' ', '1', ',', ' ', '2', ']', ',', ' ', '[', '3', ',', ' ', '4', ',', ' ', '0', ',', ' ', '3', ',', ' ', '2', ']', ',', ' ', '[', '2', ',', ' ', '2', ',', ' ', '2', ',', ' ', '1', ',', ' ', '0', ']', ']'

How do I turn a string back into a matrix?

1

There are 1 best solutions below

2
On BEST ANSWER

Here is a solution :

a = '[[0, 3, 4, 3, 2], [1, 2, 1, 2, 3], [3, 3, 3, 1, 2], [3, 4, 0, 3, 2], [2, 2, 2, 1, 0]]'

lst_lst = []
for i in a[:-1].replace('[', '').split(']'):
    lst = []
    for carac in i:
        if carac not in [',', ' ']:
            lst.append(int(carac))
    lst_lst.append(lst)
lst_lst
-> [[0, 3, 4, 3, 2], [1, 2, 1, 2, 3], [3, 3, 3, 1, 2], [3, 4, 0, 3, 2], [2, 2, 2, 1, 0]]