0

I would like to read a data from file to double nested lists. How can I do it in Python 3? I know that if I know the dimensions beforehand, I can write

# Creates a list containing 5 lists, each of 8 items, all set to 0
w, h = 8, 5;
Matrix = [[0 for x in range(w)] for y in range(h)] 

like in How to define a two-dimensional array in Python . But in my situation I read data from file and I don't know beforehand how much data there is. So the idea is to increase the matrix size while reading, like first

1 2 3

then

1 2 3
2 3 4

then

1 2 3
2 3 4
3 4 5

and so on.

Jaakko Seppälä
  • 744
  • 2
  • 7
  • 21

1 Answers1

0

you can just append to your list of rows:

Matrix = []
for row in rows:
    Matrix.append(row)

that way the matrix just grows.

you could use it like this:

from io import StringIO

matrix1_txt='''1 2 3
'''

matrix2_txt='''1 2 3
4 5 6
'''

matrix3_txt='''1 2 3
4 5 6
7 8 9
'''


Matrix = []
with StringIO(matrix3_txt) as file:
    for line in file:
        Matrix.append([int(i) for i in line.split()])

print(Matrix)  # [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

(where you'd need to replace StringIO(matrix3_txt) by open('file.txt', 'r) if your data is in a text file called file.txt)

hiro protagonist
  • 44,693
  • 14
  • 86
  • 111