I have a txt file consisting some numbers with space and I want to make it as three 4*4 matrixes in python. Each matrix is also divided with two symbols in the text file. The format of the txt file is like this:
JavaScript
x
16
16
1
1 1
2
0 0 0 0
3
0 0 0 0
4
0 0 0 0
5
0 0 0 0
6
1 1
7
0 0 0 0
8
0 0 0 0
9
0 0 0 0
10
0 0 0 0
11
1 1
12
0 0 0 0
13
0 0 0 0
14
0 0 0 0
15
0 0 0 0
16
My code is now like this but it is not showing the output I want.
JavaScript
1
5
1
file = open('inputs.txt','r')
2
a=[]
3
for line in file.readlines():
4
a.append( [ int (x) for x in line.split('1 1') ] )
5
Can you help me with that?
Advertisement
Answer
A good old pure python algorithm (assuming matrices can hold string values, otherwise, convert as required):
JavaScript
1
15
15
1
file = open("inputs.txt",'r')
2
matrices=[]
3
m=[]
4
for line in file:
5
if line=="1 1n":
6
if len(m)>0: matrices.append(m)
7
m=[]
8
else:
9
m.append(line.strip().split(' '))
10
if len(m)>0: matrices.append(m)
11
print(matrices)
12
# [[['0', '0', '0', '0'], ['0', '0', '0', '0'], ['0', '0', '0', '0'], ['0', '0', '0', '0']],
13
# [['0', '0', '0', '0'], ['0', '0', '0', '0'], ['0', '0', '0', '0'], ['0', '0', '0', '0']],
14
# [['0', '0', '0', '0'], ['0', '0', '0', '0'], ['0', '0', '0', '0'], ['0', '0', '0', '0']]]
15