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

Read List in List

I have a text file and there is 3 lines on data in it.

[1, 2, 1, 1, 3, 1, 1, 2, 1, 3, 1, 1, 1, 3, 3]
[1, 1, 3, 3, 3, 1, 1, 1, 1, 2, 1, 1, 1, 3, 3]
[1, 2, 3, 1, 3, 1, 1, 3, 1, 3, 1, 1, 1, 3, 3]

I try to open and get data in it.

with open("rafine.txt") as f:
    l = [line.strip() for line in f.readlines()]
    f.close()

now i have list in list.
if i say print(l[0]) it shows me [1, 2, 1, 1, 3, 1, 1, 2, 1, 3, 1, 1, 1, 3, 3]
But i want to get numbers in it.
So when i write print(l[0][0])
i want to see 1 but it show me [

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 can i fix this ?

>Solution :

Try:

listoflists = []
for line in f.readlines():
    lst = [int(x) for x in line.strip()[1:-1].split(", ")]
    listoflists.append(lst)

The [1,-1] will remove the first and last character (the brackets), then split(", ") will split it into a list. for x in ... will iterate over the items in this list (assigning x to each item) and int(x) will convert x to an integer. lst then will contain the list for a single line, which is appended to listoflists.

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