2014-10-22 64 views
0

這是一個神奇的方形程序,可以找出任意大小的矩陣是否爲幻方。當我運行代碼時,我得到錯誤TypeError:'int'對象不是可下標的。我決定將line = int(i)更改爲line = i,但這只是給了我另一個錯誤。不能使用numpy的TypeError:'int'對象不可迭代Python讀取文件

編輯:現在,我得到這個錯誤類型錯誤: '詮釋' 對象不是可迭代

文本文件:

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

回答

1

問題是矩陣被「扁平化」成一長排。爲了解決它,你應該閱讀&構造矩陣逐行。

變化:

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這是在矩陣的第一行的總和的問題所提供的輸入運行它。