I have a text file which contains matrix of N * M dimensions.
For example the input.txt file contains the following:
JavaScript
x
11
11
1
0,0,0,0,0,0,0,0,0,0
2
0,0,0,0,0,0,0,0,0,0
3
0,0,0,0,0,0,0,0,0,0
4
0,0,0,0,0,0,0,0,0,0
5
0,0,0,0,0,0,0,0,0,0
6
0,0,0,0,0,0,0,0,0,0
7
0,0,2,1,0,2,0,0,0,0
8
0,0,2,1,1,2,2,0,0,1
9
0,0,1,2,2,1,1,0,0,2
10
1,0,1,1,1,2,1,0,2,1
11
I need to write python script where in I can import the matrix.
My current python script is:
JavaScript
1
5
1
f = open ( 'input.txt' , 'r')
2
l = []
3
l = [ line.split() for line in f]
4
print l
5
the output list comes like this
JavaScript
1
5
1
[['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'],
2
['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'],
3
['0,0,2,1,0,2,0,0,0,0'], ['0,0,2,1,1,2,2,0,0,1'], ['0,0,1,2,2,1,1,0,0,2'],
4
['1,0,1,1,1,2,1,0,2,1']]
5
I need to fetch the values in int form . If I try to type cast, it throws errors.
Advertisement
Answer
Consider
JavaScript
1
4
1
with open('input.txt', 'r') as f:
2
l = [[int(num) for num in line.split(',')] for line in f]
3
print(l)
4
produces
JavaScript
1
2
1
[[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, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 2, 1, 0, 2, 0, 0, 0, 0], [0, 0, 2, 1, 1, 2, 2, 0, 0, 1], [0, 0, 1, 2, 2, 1, 1, 0, 0, 2], [1, 0, 1, 1, 1, 2, 1, 0, 2, 1]]
2
Note that you have to split on commas.
If you do have blank lines then change
JavaScript
1
2
1
l = [[int(num) for num in line.split(',')] for line in f ]
2
to
JavaScript
1
2
1
l = [[int(num) for num in line.split(',')] for line in f if line.strip() != "" ]
2