0

New to python and I keep getting this error when I try running my code. This is the code I'm trying to run

table=[0]*3
column=0
n=0
with open('matrix.txt','r') as f:
    numbers=f.read()
    numbers=[int(x) for x in numbers.split()]
    for i in range(3):
        table[column]=[0]*3
        for j in range(3):
            table[i][j]=numbers[n]
            n+=1
    column+=1
print(table)    

I want to make a 3x3 table of the contents in my file. the file contents are;

2 3 4 1 2 6 9 8 9

I keep getting the error message when I run it. Any ideas on how to fix it?

2
  • 1
    i think you should iterate column and not collumn line before the last one Commented Mar 31, 2017 at 10:43
  • Do you want a list of list? something like [[2,3,4], [1,2,5]...] right? Commented Mar 31, 2017 at 10:45

3 Answers 3

4

You make it more complicated than it has to be:

numbers = [2, 3, 4, 1, 2, 6, 9, 8, 9]
table = [numbers[i:i+3] for i in range(0, len(numbers), 3)]
Sign up to request clarification or add additional context in comments.

Comments

3

You are incrementing the column outside of the outer for loop. Moreover, it is misspelled.

1 Comment

this answer is the right one, fix your indent and the column and with it the code works fine for me
1

how about:

import numpy as np 
with open('matrix.txt','r') as f:
    numbers=f.read()
    table =np.array([int(x) for x in numbers.split()]).reshape((3,3))
print(table)

if you really insist that your table is not a numpy array just convert it to a list:

table = table.tolist()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.