How do I Store input data into more than one matrices in Python?

Viewed 22

I have a text file that contains more than one matrix:

A 3 3
1 1 1
2 2 2
3 3 3
[space]
B 3 2
9 9 9
7 7 7
[space]
C 2 2
7 7
7 7

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?

1 Answers

That file can be parsed like this:

import numpy as np

SPLIT_SEQUENCE = '[space]'
INPUT_FILE = 'test.txt'

with open(INPUT_FILE) as f:
    matrix_data = f.read().split(SPLIT_SEQUENCE)

matrixes = {}
for d in matrix_data:
    parts = [s for s in d.split('\n') if s]
    header = parts[0].split()
    name, shape = header[0], (int(header[2]), int(header[1]))
    matrixes[name] = np.zeros(shape)

    for i, part in enumerate(parts[1:]):
        for j, value in enumerate(part.split()):
            matrixes[name][i, j] = int(value)

matrixA = matrixes['A']
matrixB = matrixes['B']
matrixC = matrixes['C']

Result:

print(matrixA)
[[1. 1. 1.]
 [2. 2. 2.]
 [3. 3. 3.]]

print(matrixB)
[[9. 9. 9.]
 [7. 7. 7.]]

print(matrixC)
[[7. 7.]
 [7. 7.]]

Or without numpy (i.e. only using lists):

SPLIT_SEQUENCE = '[space]'
INPUT_FILE = 'test.txt'

with open(INPUT_FILE) as f:
    matrix_data = f.read().split(SPLIT_SEQUENCE)

matrixes = {}
for d in matrix_data:
    parts = [s for s in d.split('\n') if s]
    name = parts[0].split()[0]
    matrixes[name] = []

    for i, part in enumerate(parts[1:]):
        matrixes[name].append([])
        for value in part.split():
            matrixes[name][i].append(int(value))

matrixA = matrixes['A']
matrixB = matrixes['B']
matrixC = matrixes['C']

Result:

print(matrixA)
[[1, 1, 1], [2, 2, 2], [3, 3, 3]]

print(matrixB)
[[9, 9, 9], [7, 7, 7]]

print(matrixC)
[[7, 7], [7, 7]]
Related