I need to convert a string representation into a 2 dimensional list.
I am trying to read inputs from a text file. All inputs follow a standard format where each line represents a different variable. When I read the following line from the input file using f.readline():
[[0, 2, 1, 2, 3, 0], [2, 0, 3, 0, 1, 0], [2, 0, 0, 3, 3, 0], [0, 2, 3, 0, 0, 3], [1, 2, 3, 1, 0, 2], [2, 1, 0, 1, 3, 0]]
This line is read in as a string, but I need it converted to a 2 dimensional list. A constraint for this project is I cannot use any packages, only base python.
How do I do this?
>Solution :
Something like that should work:
text = "[[0, 2, 1, 2, 3, 0], [2, 0, 3, 0, 1, 0], [2, 0, 0, 3, 3, 0], [0, 2, 3, 0, 0, 3], [1, 2, 3, 1, 0, 2], [2, 1, 0, 1, 3, 0]]"
output = []
for sublist in text.split('], '):
sublist = sublist.replace('[', '').replace(']', '')
data = []
for number in sublist.split(', '):
data.append(int(number))
output.append(data)
print(output)
Using list comprehension:
text = "[[0, 2, 1, 2, 3, 0], [2, 0, 3, 0, 1, 0], [2, 0, 0, 3, 3, 0], [0, 2, 3, 0, 0, 3], [1, 2, 3, 1, 0, 2], [2, 1, 0, 1, 3, 0]]"
output = [[int(number) for number in sublist.replace('[', '').replace(']', '').split(', ')] for sublist in text.split('], ')]
print(output)