Home > Software design >  Reading Matrix from file
Reading Matrix from file

Time:05-16

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?

CodePudding user response:

One option is to use groupby:

from itertools import groupby

matrices = []

with open('inputs.txt', 'r') as f:
    for separator, lines in groupby(f, lambda line: line.strip() == '1 1'):
        if not separator:
            matrices.append([[int(x) for x in line.split()] for line in lines])

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]]]

CodePudding user response:

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']]]
  • Related