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 [
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.