这是一个魔术方块程序,可以找出任何大小的矩阵是否是魔术方块。当我运行代码时,我得到错误TypeError:' int'对象不可订阅。我决定将line = int(i)更改为line = i,但这只是给了我另一个错误。不能使用numpy
编辑:现在我收到此错误TypeError:' int'对象不可迭代
文本文件:
1 1
6 8
这是代码:
def main():
filNam = "matrix8.txt"
matrix = (readMatrix(filNam))
rowNum = 0
colNum = 0
print(rowSum(matrix, rowNum))
def readMatrix(filNam):
matrixList = []
numFile = open(filNam, "r")
lines = numFile.readlines()
for line in lines:
line = line.split()
row = []
for i in line:
row.append(int(i))
matrixList.append(row)
return matrixList
def eachNumPresent(matrix):
if len(matrix) % 2 != 0:
return False
else:
return True
def rowSum(matrix, rowNum):
for row in matrix[rowNum]:
row = sum(int(row))
rowNum = rowNum + 1
return i
def colSum(matrix):
length = len(matrix)
col_rows = 0
for i in range(length):
col_rows = col_rows + matrix[i][0]
return col_rows
main()
答案 0 :(得分:1)
问题是矩阵变得扁平化了#34;进入一个长排。为了解决这个问题,你应该阅读&逐行构造矩阵。
变化:
def readMatrix(filNam):
matrixList = []
numFile = open(filNam, "r")
lines = numFile.readlines()
for line in lines:
line = line.split()
for i in line:
line = int(i)
matrixList.append(line)
return matrixList
为:
def readMatrix(filNam):
matrixList = []
numFile = open(filNam, "r")
lines = numFile.readlines()
for line in lines:
line = line.split()
row = [] # 1st change
for i in line:
row.append(int(i)) # 2nd change
matrixList.append(row) #3rd change
return matrixList
更改代码并在问题中提供的输入上运行它打印2
,这是矩阵中第一行的总和。