Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

convert string into 2 dimensional list with no imports

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading