I am trying to parse data from a text file. I want to store each of the 9 numbers in a separate list, making it a list of lists. Here's what I have, I am not quite sure how to go from here.
file = open("data.txt", 'r')
Result = [line.split(',') for line in file.readlines()]
print(Result)
Here is what the txt file looks like:
3 7 5
0 4 2
8 1 6
2 6 3
1 0 8
5 4 7
4 1 6
0 8 7
2 3 5
7 2 6
4 1 3
8 0 5
This is my output:
[['3 7 5 \n'], ['0 4 2 \n'], ['8 1 6 \n'], ['\n'], ['2 6 3 \n'], ['1 0 8 \n'], ['5 4 7 \n'], ['\n'], ['4 1 6 \n'], ['0 8 7 \n'], ['2 3 5 \n'], ['\n'], ['7 2 6 \n'], ['4 1 3 \n'], ['8 0 5 \n'],['\n']]
you split() on space which is default
res=[line.split() for line in file.readlines() if line.strip()]
>>>res
[['3', '7', '5'], ['0', '4', '2'], ['8', '1', '6'], ['2', '6', '3'], ['1', '0', '8'], ['5', '4', '7'], ['4', '1', '6'], ['0', '8', '7'], ['2', '3', '5'], ['7', '2', '6'], ['4', '1', '3'], ['8', '0', '5']]
if you want in a list of list
res =[]
sub =[]
for line in file.readlines():
if line.strip():
sub.append(line.split())
else:
res.append(sub)
sub=[]
>>>res
[[['3', '7', '5'], ['0', '4', '2'], ['8', '1', '6']], [['2', '6', '3'], ['1', '0', '8'], ['5', '4', '7']], [['4', '1', '6'], ['0', '8', '7'], ['2', '3', '5']]]
if you want all 9 numbers in in a single list, use extend instead of append
res =[]
sub =[]
for line in file.readlines():
if line.strip():
sub.extend(line.split())
else:
res.append(sub)
sub=[]
>>>res
[['3', '7', '5', '0', '4', '2', '8', '1', '6'], ['2', '6', '3', '1', '0', '8', '5', '4', '7'], ['4', '1', '6', '0', '8', '7', '2', '3', '5']]
if you want to convert all to integers convert using int()
sub.extend([int(x) for x in line.split()])
You can use below logic.
listoflists = []
list = []
file = open('data.txt', 'r')
for line in file.readlines():
for n in line:
if (n!=" " and n!="\n"):
list.append(n)
if line == '\n':
listoflists.append(list)
list=[]
print(listoflists)
Result [['3', '7', '5', '0', '4', '2', '8', '1', '6'], ['2', '6', '3', '1', '0', '8', '5', '4', '7'], ['4', '1', '6', '0', '8', '7', '2', '3', '5']]
Try this,you can define number of items for each list and pass it to chunks function
file = open("data.txt", 'r')
l = list(filter(None,file.read().splitlines()))
l = list(filter(None," ".join(l).split(' ')))
def chunks(li,n):
for i in range(0,len(li),n):
yield li[i:i+n]
out = list(chunks(l,9))
output
[['3', '7', '5', '0', '4', '2', '8', '1', '6'],
['2', '6', '3', '1', '0', '8', '5', '4', '7'],
['4', '1', '6', '0', '8', '7', '2', '3', '5'],
['7', '2', '6', '4', '1', '3', '8', '0', '5']]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.