Assuming your file is not humongous, it is numerical and 4x4, the easiest method is:
- read all the file
- split it in blocks with the
1 1\n
separator
- discard the separator items (
if block
)
- convert block to vector with
split
- reshape each vector to 4x4
- make it integer
In a single line:
matrixes = [np.reshape(np.array(block.split()),(4,4)).astype(int) for block in open('inputs.txt').read().split('1 1\n') if block]
Caveat: if a matrix reads x x 1 1
in one of its rows, it will be considered a split regardless. Using a value that could be used in the matrix is not a good idea.
That could be prevented splitting on \n1 1\n
, and removing by hand the first 4 characters (1 1\n
). Also this implementation may be more efficient, flattening everything and then reshaping:
dd = open('inputs.txt').read()[4:]
nmats = dd.count('\n1 1\n') +1
matrixes = np.reshape(np.array(dd.replace('\n1 1\n',' ').split()).astype(int),(nmats,4,4))
This last option returns it as a single 3D matrix:
>>> matrixes
array([[[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]]])
>>> matrixes[0]
array([[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0]])
1 1
, do they separate matrixes? – Duelloread()
and later split it withsplit('1 1')
to create 4 strings with matrixes. And later you would have to split these strings using"\n"
andspace
. – Granophyreprint()
to see what you get inline
andline.split('1 1')
andx
(before you useint()
. It is called"print debuging"
and it helps to see what code is doing. – Granophyre