pythonarraysmagic-square

How to turn a line in a file into a 2d array


I'm fairly new to python and I've been struggling with coding a program that will take a line in a file as input to verify a Lo Shu Magic Square. What i need to do is read one line in the file at a time and with each line 1 2 3 4 5 6 7 8 9 for instance, and convert that into a 2d array like [[1,2,3],[4,5,6],[7,8,9]] The first three numbers correspond to the values in the first row of the magic square, the next three values correspond to the second row, and the last three values correspond to the last row.

So far I've tried

def main():
  data = []
  for line in open('Magic Square Input.txt'):
    items = line.split(" ")
    temp = 0
    setOfThree = []
    for item in items:

        if(len(item) > 1):
            item = item[0:1]

        if(item != " "):
            setOfThree.append(item)
            temp += 1


        if(temp == 3):
            test = []
            test = setOfThree[:]
            test = [int(x) for x in test]
            data.append(test)

But that only gives me

[[4, 3, 8]]
[[4, 3, 8], [8, 3, 4]]
[[4, 3, 8], [8, 3, 4], [6, 1, 8]]
[[4, 3, 8], [8, 3, 4], [6, 1, 8], [6, 9, 8]]
[[4, 3, 8], [8, 3, 4], [6, 1, 8], [6, 9, 8], [6, 1, 8]]
[[4, 3, 8], [8, 3, 4], [6, 1, 8], [6, 9, 8], [6, 1, 8], [6, 1, 3]]
[[4, 3, 8], [8, 3, 4], [6, 1, 8], [6, 9, 8], [6, 1, 8], [6, 1, 3], [5, 5, 5]]

The contents of the text file are

4 3 8 9 5 1 2 7 6
8 3 4 1 5 9 6 7 2
6 1 8 7 5 3 2 9 4
6 9 8 7 5 3 2 1 4
6 1 8 7 5 3 2 1 4
6 1 3 2 9 4 8 7 5
5 5 5 5 5 5 5 5 5

So I feel like im on the right track, but its only appending the first three items of each line to data and i cant figure out why


Solution

  • Lines have always 9 elements so

    line = "1 2 3 4 5 6 7 8 9"
    
    items = line.split()
    
    result = [items[0:3], items[3:6], items[6:9]]
    
    print(result)
    

    EDIT: the same with all lines

    lines = """4 3 8 9 5 1 2 7 6
    8 3 4 1 5 9 6 7 2
    6 1 8 7 5 3 2 9 4
    6 9 8 7 5 3 2 1 4
    6 1 8 7 5 3 2 1 4
    6 1 3 2 9 4 8 7 5
    5 5 5 5 5 5 5 5 5"""
    
    data = []
    
    for line in lines.split('\n'):
    
        items = line.split()
    
        data.append([items[0:3], items[3:6], items[6:9]])
    
    print(data)
    

    If you need more universal - for different N

    N = 3
    
    data = []
    
    for line in lines.split('\n'):
    
        items = line.split()
        array = []
    
        while items:
            array.append(items[:N])
            items = items[N:]
    
        data.append(array)
    
    print(data)