1

I have a text file with multiple matrices like this:

4 5 1
4 1 5
1 2 3
[space]
4 8 9
7 5 6
7 4 5
[space]
2 1 3
5 8 9
4 5 6

I want to read this input file in python and store it in multiple matrices like:

matrixA = [...] # first matrix
matrixB = [...] # second matrix

so on. I know how to read external files in python but don't know how to divide this input file in multiple matrices, how can I do this?

Thank you

1
  • 1
    How many matrices will you have when all is said and done? Variable amount? 10? 1,000,000? And what do you plan to do with them once they're stored the way you want? Is this code you'll re-use over and over again or for a one-time thing? Commented Mar 10, 2019 at 5:09

2 Answers 2

1

You can write a code like this:

all_matrices = []  # hold matrixA, matrixB, ...
matrix = []  # hold current matrix
with open('file.txt', 'r') as f:
    values = line.split()
    if values:  # if line contains numbers
        matrix.append(values)
    else:  # if line contains nothing then add matrix to all_matrices
        all_matrices.append(matrix)
        matrix = []
# do what every you want with all_matrices ...
Sign up to request clarification or add additional context in comments.

1 Comment

You forgot to close the file. with open(...) as f: is a very useful idiom. And a small note: strip is not needed before spilit.
0

I am sure the algorithm could be optimized somewhere, but the answer I found is quite simple:

file = open('matrix_list.txt').read() #Open the File
matrix_list = file.split("\n\n") #Split the file in a list of Matrices
for i, m in enumerate(matrix_list): 
    matrix_list[i]=m.split("\n") #Split the row of each matrix
    for j, r in enumerate(matrix_list[i]): 
        matrix_list[i][j] = r.split() #Split the value of each row

This will result in the following format:

[[['4', '5', '1'], ['4', '1', '5'], ['1', '2', '3']], [['4', '8', '9'], ['7', '5', '6'], ['7', '4', '5']], [['2', '1', '3'], ['5', '8', '9'], ['4', '5', '6']]]

Example on how to use the list:

print(matrix_list) #prints all matrices
print(matrix_list[0]) #prints the first matrix
print(matrix_list[0][1]) #prints the second row of the first matrix
print(matrix_list[0][1][2]) #prints the value from the second row and third column of the first matrix

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.