我的代码与输出的外观完全相同,但由于某些原因,它是错误的



我正在尝试编写一个程序,其中函数接受文件名和元组列表。列表中的每个元组将包含5个条目,其中第一个、第三个和第四个条目是int,第二个条目是字符串,第五个条目是浮点。该程序的目标是将每个元组的5个元素写在单独的一行上。例如,文件中一行的元组1中的所有5个,第二行的元组2中的所有五个,等等。

现在,我的代码给了我测试用例所期望的确切输出,但出于某种原因,它说我的答案是不正确的。我确信问题在于我的代码在每行的末尾都添加了一个额外的空格。如何修复我的代码?

def write_1301(filename, tuple_list):
file = open(filename, "w")
for tup in tuple_list:
for i in range(0, len(tup)):
print(tup[i], file = file, end = " ")
print(file = file)
file.close()

#The code below will test your function. It's not used
#for grading, so feel free to modify it! You may check
#output.cs1301 to see how it worked.
tuple1 = (1, "exam_1", 90, 100, 0.6)
tuple2 = (2, "exam_2", 95, 100, 0.4)
tupleList = [tuple1, tuple2]
write_1301("output.cs1301", tupleList)

测试用例示例:

We tested your code with filename = "AutomatedTestOutput-MAZIxa.txt", tuple_list = [(1, 'quiz_1', 13, 20, 0.17), (2, 'exam_1', 55, 85, 0.12), (3, 'exam_2', 15, 20, 0.1), (4, 'assignment_1', 15, 30, 0.11), (5, 'test_1', 21, 35, 0.17), (6, 'quiz_2', 44, 70, 0.11), (7, 'test_2', 85, 100, 0.12), (8, 'test_3', 35, 50, 0.1)]. We expected the file to contain this:
1 quiz_1 13 20 0.17
2 exam_1 55 85 0.12
3 exam_2 15 20 0.1
4 assignment_1 15 30 0.11
5 test_1 21 35 0.17
6 quiz_2 44 70 0.11
7 test_2 85 100 0.12
8 test_3 35 50 0.1
However, the file contained this:
1 quiz_1 13 20 0.17 
2 exam_1 55 85 0.12 
3 exam_2 15 20 0.1 
4 assignment_1 15 30 0.11 
5 test_1 21 35 0.17 
6 quiz_2 44 70 0.11 
7 test_2 85 100 0.12 
8 test_3 35 50 0.1

我尝试过以各种方式使用end=,但没有成功,我很困惑。

您的问题是手动单独编写每个元素,并在每个元素后面添加一个空格。这意味着,在编写最后一个元素时,还添加了一个尾随空格。所以你的输出看起来很匹配,但实际上你的行都有一个尾部空间。

相反,您可以使用字符串联接将列表中的所有元素与一个空格联接起来。这将只在元素之间添加空格,而不是在每个元素之后添加空格。但是,它希望传递给它的所有值都是字符串。因此,我们可以使用列表理解,将元组中的所有元素转换为字符串,并将字符串列表传递给联接函数。

def write_1301(filename, tuple_list):
with open(filename, "w") as file:
for tup in tuple_list:
print(" ".join([str(t) for t in tup]), file=file)

# The code below will test your function. It's not used
# for grading, so feel free to modify it! You may check
# output.cs1301 to see how it worked.
tuple1 = (1, "exam_1", 90, 100, 0.6)
tuple2 = (2, "exam_2", 95, 100, 0.4)
tupleList = [tuple1, tuple2]
write_1301("output.cs1301", tupleList)

最新更新