Read List in List
Question:
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 ?
Answers:
You can use literal_eval
to parse the lines from the file & build the matrix:
from ast import literal_eval
with open("test.txt") as f:
matrix = []
for line in f:
row = literal_eval(line)
matrix.append(row)
print(matrix[0][0])
print(matrix[1][4])
print(matrix[2][8])
result:
1
3
1
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
.
import json
with open("rafine.txt") as f:
for line in f.readlines():
line = json.loads(line)
print(line)
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 ?
You can use literal_eval
to parse the lines from the file & build the matrix:
from ast import literal_eval
with open("test.txt") as f:
matrix = []
for line in f:
row = literal_eval(line)
matrix.append(row)
print(matrix[0][0])
print(matrix[1][4])
print(matrix[2][8])
result:
1
3
1
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
.
import json
with open("rafine.txt") as f:
for line in f.readlines():
line = json.loads(line)
print(line)