bigl
bigl

Reputation: 1083

python list of lists insert newline

I am reading in a file which contains a matrix of integers each separated by a comma. So far I have:

def open_file(file):
    with open('network.txt') as f:
        Alist = []
        for line in f:
            part = []
            for x in line.split(','):
                part.append(int(x))
            Alist.append(part)
    print Alist

open_file(file)

This successfully displays the values but displays them in a straight line and that is not how I need them to be. For each "row" of integers I would like a new row to begin so they build up to a row of 6x6. I have attempted to print newlines at different parts in the code but it has not worked and instead prints newlines equal to the amount of lines it detects in the entire file before displaying the numbers. When dealing with matrices would it be best to remove any commas?

Also upon creation of the matrix I intend to start at lets say 1,1 and then find any neighbours (1,2 and 2,1). Could I be pointed in the correct direction of how this would be accomplished as my searches have returned no usable results. I could easily be searching in the wrong way though.

This is homework.

Upvotes: 2

Views: 3497

Answers (2)

Zlatin Zlatev
Zlatin Zlatev

Reputation: 3088

Or somewhat more "pythonic" way

print "\n".join(str(row) for row in Alist)

Upvotes: 1

Jared
Jared

Reputation: 26397

Is this what you are looking for?

for row in Alist:
    print row

To move to adjacent cells in your grid all you need to do is increment the index for the row or column. Moving from Alist[0][0] to the right would then be Alist[0][1] and down would be Alist[1][0].

Upvotes: 3

Related Questions