Marco Souza
Marco Souza

Reputation: 3

reading matrices with different sizes from a input file

I am trying to make a function that will recieve a input file containing matrices, then will store those matrices inside another matrix, the input file format will always be the same.

This is what I've tried:

with open("input.txt", "r") as file:
    r = input.read()
    matrix = [[num for num in line] for line in r if line.strip() != " " ]

input.txt:

3 4

4 2 3 1

2 1 0 0

0 0 1 0
2 0 0 1
0 1 2 0

2 0 5 1
1 0 1 0
2 1 0 0

**The output of the code: **

[['3'], [' '], ['4'], ['\n'], ['\n'], ['4'], [' '], ['2'], [' '], ['3'], [' '], ['1'], ['\n'], ['\n'], ['2'], [' '], ['1'], [' '], ['0'], [' '], ['0'], ['\n'], ['\n'], ['0'], [' '], ['0'], [' '], ['1'], [' '], ['0'], ['\n'], ['2'], [' '], ['0'], [' '], ['0'], [' '], ['1'], ['\n'], ['0'], [' '], ['1'], [' '], ['2'], [' '], ['0'], ['\n'], ['\n'], ['2'], [' '], ['0'], [' '], ['5'], [' '], ['1'], ['\n'], ['1'], [' '], ['0'], [' '], ['1'], [' '], ['0'], ['\n'], ['2'], [' '], ['1'], [' '], ['0'], [' '], ['0']]

Expected output:

[[3, 4],

[4, 2, 3, 1],

[2, 1, 0, 0],

[[0, 0, 1, 0],
[2, 0, 0, 1],
[0, 1, 2, 0]],

[[2, 0, 5, 1],
[1, 0,1, 0],
[2, 1, 0 ,0]]]

Upvotes: 0

Views: 43

Answers (1)

Rahul K P
Rahul K P

Reputation: 16081

You can do this.

with open("input.txt", "r") as file:
    r = file.read()
    [line.split() for line in list(map(str.strip, filter(None, r)))]

filter to remove the '' values

map is used to apply a strip for each element in the list.

Output:

[['3', '4'],
 ['4', '2', '3', '1'],
 ['2', '1', '0', '0'],
 ['0', '0', '1', '0', '2', '0', '0', '1', '0', '1', '2', '0'],
 ['2', '0', '5', '1', '1', '0', '1', '0', '2', '1', '0', '0']]

EDIT

Since OP revered his input changed the answer according to it.

You can do this with re, first it's split with two newlines.

import re

result = []
with open("input.txt", "r") as file:
    r = file.read()
    for item in re.split(r'\n\n', r):
        if '\n' in item:
            result.append([i.split() for i in item.split('\n')])
        else:
            result.append(item.split())

Result

[['3', '4'],
 ['4', '2', '3', '1'],
 ['2', '1', '0', '0'],
 [['0', '0', '1', '0'], ['2', '0', '0', '1'], ['0', '1', '2', '0']],
 [['2', '0', '5', '1'], ['1', '0', '1', '0'], ['2', '1', '0', '0']]]

Upvotes: 1

Related Questions