简体   繁体   English

如何修复我的:TypeError:'int' 对象不支持项目分配

[英]How to fix my: TypeError: 'int' object does not support item assignment

New to python and I keep getting this error when I try running my code. python的新手,当我尝试运行我的代码时,我不断收到这个错误。 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.我想在我的文件中制作一个 3x3 的内容表。 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?关于如何解决它的任何想法?

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)]

You are incrementing the column outside of the outer for loop.您正在增加外部 for 循环之外的列。 Moreover, it is misspelled.此外,它拼写错误。

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:如果你真的坚持你的表不是一个 numpy 数组,只需将它转换为一个列表:

table = table.tolist()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM