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:
1 1
0 0 0 0
0 0 0 0
0 0 0 0
0 0 0 0
1 1
0 0 0 0
0 0 0 0
0 0 0 0
0 0 0 0
1 1
0 0 0 0
0 0 0 0
0 0 0 0
0 0 0 0
My code is now like this but it is not showing the output I want.
file = open('inputs.txt','r')
a=[]
for line in file.readlines():
a.append( [ int (x) for x in line.split('1 1') ] )
Can you help me with that?
A good old pure python algorithm (assuming matrices can hold string values, otherwise, convert as required):
file = open("inputs.txt",'r')
matrices=[]
m=[]
for line in file:
if line=="1 1\n":
if len(m)>0: matrices.append(m)
m=[]
else:
m.append(line.strip().split(' '))
if len(m)>0: matrices.append(m)
print(matrices)
# [[['0', '0', '0', '0'], ['0', '0', '0', '0'], ['0', '0', '0', '0'], ['0', '0', '0', '0']],
# [['0', '0', '0', '0'], ['0', '0', '0', '0'], ['0', '0', '0', '0'], ['0', '0', '0', '0']],
# [['0', '0', '0', '0'], ['0', '0', '0', '0'], ['0', '0', '0', '0'], ['0', '0', '0', '0']]]