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
Ehsan Mohammadi
1,3261 gold badge17 silver badges22 bronze badges
-
1How 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?Jarad– Jarad2019年03月10日 05:09:18 +00:00Commented Mar 10, 2019 at 5:09
2 Answers 2
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 ...
answered Mar 10, 2019 at 5:09
Mojtaba Kamyabi
3,6703 gold badges33 silver badges52 bronze badges
Sign up to request clarification or add additional context in comments.
1 Comment
VPfB
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.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
answered Mar 10, 2019 at 5:41
victortv
9,1122 gold badges29 silver badges30 bronze badges
Comments
Explore related questions
See similar questions with these tags.
lang-py