OultimoCoder
OultimoCoder

Reputation: 294

How to create an array of matrices read from a text file

If I have a text file where each line is a line in a matrix and each matrix is separated by a new line e.g.

1234
1234

2345
2345

How would I go about creating an array of those matrices (Without using numpy).

For 1 matrix I do:

with open("matrix.txt", "r") as file:
    matrix=[line.split() for line in file]

To extrapolate this code for multiple matrices I tried doing:

x=0
matrix=[]
with open("matrix.txt", "r") as file:
    for line in file:
        if line == "\n":
           x+=1
        else:
            matrix[x].append([line.split()])
print(matrix)

Where the line from a textfile gets appended to a matrix like before but if it encounters a newline it appends the next lines to the next index of the 3d array so I end up with an array of arrays.

The code I have listed gives me and out of index error which I know should happen because when I increase the matrix index with x it doesn't actually exist as I have never created it.

I am stuck and could do with some help. Please ask if you need me to clarify something or if I haven't explained something well enough. Thanks!

Edit: Output would look something like [[[1,2,3,4], [1,2,3,4]], [[2,3,4,5],[2,3,4,5]]]

So matrix[0][1][2] would access the first matrix and retrieve 3.

Upvotes: 0

Views: 816

Answers (2)

Pluriscient
Pluriscient

Reputation: 125

Simply check the length of your list and add an item if necessary:

EDIT: since your working method didn't split into seperate integers, it would be weird for the extended version to. Updated to edited question

content = "1234\n1234\n\n2345\n2345"

x=0
matrixes = []
for line in content.split('\n'):
    if line is "":
        x+=1
    else:
        if len(matrixes) <= x:
            matrixes.append([[int(x) for x in list(line)]])
        else:
            matrixes[x].append([int(x) for x in list(line)])

print(matrixes[0][0][0]) results in: 1

(link to updated example: https://repl.it/EDtz/0)

Upvotes: 0

maki
maki

Reputation: 431

Ok, try this::

x=0
matrix=[]
row = []
with open("matrix.txt", "r") as file:
    for line in file:
        line = line.strip("\n")
        if line == "":
           matrix.append(row)
           row = []
        else:
            row.append([int(x) for x in list(line)])

if (len(row) > 0):
    matrix.append(row)

print(matrix)

Result: [[[1, 2, 3, 4], [1, 2, 3, 4]], [[2, 3, 4, 5], [2, 3, 4, 5]]]

Upvotes: 1

Related Questions