2016-11-01 66 views
-2

我目前正在開始編程課程,需要幫助糾正一個函數。我需要列表中的所有元素都是整數,而不是字符串。要做到這一點,我需要從函數中更改一行,但我不知道要更改哪一行!任何幫助將不勝感激。需要列表的所有元素是整數

def read_magic_square(filename): 
    """ 
    Read values from a file into a 2D list 

    Parameter: 
    filename: the name of the file 

    Returns a 2D list of integer values read. 
    """ 

    infile = open(filename, "rt") 
    square = [] # start with an empty list 

    for line in infile: # read text from file 
     row = [] 
     numbers = line.split() 

     # Loop through the list of numbers. 
     # Append each number to the row. 
     for num in numbers: 
      row.append(num) 

     if len(row) > 0: # Don't count blank lines 
      square.append(row) # Append the row to the 2D list 

    return square 
+0

'row.append(int(num))'。 – Evert

+0

請確保您的整個代碼格式化在代碼塊中;前兩行是在它之外,讓你的代碼難以閱讀。 – Evert

回答

1

爲了避免錯誤,如果有該行的字符串,你只能改變追加線是(你可以改變invalid_replacement是任何你想要的,在這裏我把它作爲零)

invalid_replacement = 0 
try: 
    row.append(int(num)) 
except: 
    row.append(invalid_replacement) 
相關問題