我目前正在开始编程课程,需要帮助纠正功能。我需要此列表中的所有元素都是整数而不是字符串。要做到这一点,我需要从函数中更改一行,但我不知道要更改哪一行!任何帮助将不胜感激。
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 :(得分:1)
为避免错误,如果行中有字符串,则只能将附加行更改为(您可以将invalid_replacement
更改为您想要的任何内容,此处我将其设置为零)< / EM>:
invalid_replacement = 0
try:
row.append(int(num))
except:
row.append(invalid_replacement)