Python - 比较两个列表并获得不正确的结果

时间:2017-11-23 18:17:28

标签: python

该计划的目标是将学生答案列表与正确答案列表进行比较,并计算正确答案的数量。答案键存储为字符串列表,学生答案从文本文件中读取,然后转换为大写以匹配答案键。

#Read student answer file
student_answers = infile.read()
#Convert student answer to all caps
student_answers = [answer.upper() for answer in student_answers]

我的程序运行没有错误,但比较两个列表的结果不正确。只有3个答案显示正确,并且有20个正确的答案。下面是我到目前为止的相关代码,并且还包含了输出Program Output Image的屏幕截图。只有问题1,3,5,7和25应被标记为不正确。我仔细检查了两个列表,它们包含正确的信息,因此它没有输入错误。任何有关我可能出错的指导都将不胜感激。

for studentLine, keyLine in zip(Student, TestKey):
    keyAnswer = keyLine.split()
    studentAnswer = studentLine.split()
    #Compare student answer to test key
    if studentAnswer == keyAnswer:
        correct += 1
        percent_score += 4
        print('Good job! Question ', index + 1, 'is correct!')
        index +=1
    if studentAnswer != keyAnswer:
        incorrect += 1
        incorrect_list.append(index + 1)
        print('The correct answer to question ', index + 1, 'is ', TestKey[index])
        index +=1

1 个答案:

答案 0 :(得分:0)

我认为你错误地拆分而不是剥离。

所以你应该使用:

keyAnswer = keyLine.strip()
studentAnswer = studentLine.strip()