Reputation: 201
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?
Upvotes: 1
Views: 137
Reputation: 1001
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]]]
Upvotes: 2
Reputation: 22564
Now that you have strings, split each string on space and convert each little string to an integer. After that, you can convert each list of strings to a square "matrix" (list of lists).
An additional point: do not use list
as a variable name. That conflicts with the built-in list
type. In this code I used the name mylist
.
newlist = [[int(nstr) for nstr in v.split()] for v in mylist]
# Now convert each list of strings to a square "matrix" (list of lists)
However, note that the approach given by @Selcuk in his comment is a better way to solve your overall problem. Though it would be a little easier to read the entire file into memory and split on the stars, then split each line into its integers. This would result in easier code but larger memory usage.
Upvotes: 0