I know there are related threads, but I've searched and none of them helped me with my problem.
I have a input text file with square matrices that looks as follows:
1 2 3
4 5 6
7 8 9
*
10 11 12 13 14
15 16 17 18 19
20 21 22 23 24
25 26 27 28 29
30 31 32 33 34
Now there could be more matrices following, all with a *
in between them.
I want to separate the matrices (without using numpy!) and then using list within lists to work with them (list comprehension might be useful I guess), all the entries would be integers. The first matrix would then look as follows [[1,2,3],[4,5,6],[7,8,9]]
and the second one would be [[10,11,12,13,14],[15,16,17,18,19],[20,21,22,23,24],[25,26,27,28,29],[31,31,32,33,34]]
and so on.
My plan was to separate the matrices in their own list entries and then (using the fact that the matrices are square, and therefore it can easily be determined how many integers one list entry should contain) using some list comprehension to change the strings into integers. But I'm stuck at the very beginning.
matrix = open('input.txt','r').read()
matrix = matrix.replace('\n',' ')
list = matrix.split('* ')
Now if I print list
I get ['1 2 3 4 5 6 7 8 9', '10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34']
The problem is that I'm now stuck with two strings instead of a list of integers.
Any suggestions?
mat_list = [[[int(num_str) for num_str in line.split()] for line in inner_mat.split('\n')] for inner_mat in open('input_mat.txt','r').read().split('\n*\n')]
[[[1, 2, 3], [4, 5, 6], [7, 8, 9]], [[10, 11, 12, 13, 14], [15, 16, 17, 18, 19], [20, 21, 22, 23, 24], [25, 26, 27, 28, 29], [30, 31, 32, 33, 34]]]