Skip to main content
 首页 » 编程设计

python之使用 Python 比较列表

2025年02月15日9kuangbin

我是 python 的新手,这学期才开始学习这门类(class)。我正在努力寻找一种方法来编写代码,该代码采用正确答案并将它们存储为列表,然后从 txt 文件中读取学生对 20 个问题中每一个问题的答案并将答案存储在另一个列表中。之后我想比较列表,然后打印他们的答案,程序将显示一条消息,指示学生是否通过(15 或更大的正确是通过)以及总数正确和总数不正确。所以例如正确答案为 A, C, A, A, D, B, C, A, C, B, A, D, C, A, D, C, B, B, D, A. 因为学生的答案只是创造你的自己的文本文件进行测试。任何帮助将不胜感激我当前的格式似乎不起作用,如下所示。

def main():

total = 0 
index = 0 
answers = [ 'A', 'C', 'A', 'A', 'D',\ 
            'B', 'C', 'A', 'C', 'B',\ 
            'A', 'D', 'C', 'A', 'D',\ 
            'C', 'B', 'B', 'D', 'A'] 
 
student_answers = open('student_solution.txt', 'r') 
 
for answer in student_answers: 
    print(answer.strip()) 
 
    while index in answers == student_answers: 
        if student_answers[0] == answers[0]: 
            total +=1 
        else: 
            total +=0 
 
 
 
student_answers.close() 
print('Total correct answers: ', total) 
print('Total of incorrect answers: ', 20 - total) 
 
if total >= 15: 
    print('Congratulations! You passed the exam.') 
else: 
    print('Sorry, you have failed the exam.') 

主要()

这是更新后的程序,但似乎仍然存在问题。我使用的学生答案是 A C A A D B C A C B A D C A D C B B D A C A A D B C A C B A D C A D C B B D D

def main():

total = 0 
index = 0 
answers = [ 'A', 'C', 'A', 'A', 'D',\ 
            'B', 'C', 'A', 'C', 'B',\ 
            'A', 'D', 'C', 'A', 'D',\ 
            'C', 'B', 'B', 'D', 'A'] 
 
infile = open('student_solution.txt', 'r') 
 
student_answers = infile.readline() 
infile.close() 
print(student_answers) 
 
for answer in student_answers: 
    for y in range(len(answer)): 
        if answer[y] == answers[y]: 
            total += 1 
 
 
print('Total correct answers: ', total) 
print('Total of incorrect answers: ', 20 - total) 
 
if total >= 15: 
        print('Congratulations! You passed the exam.') 
else: 
        print('Sorry, you have failed the exam.') 

主要()

请您参考如下方法:

您可以计算总数以这种方式压缩两个列表

total = 0 
for stdnt_ans,correct_ans in zip(student_answers, answers): 
    if stdnt_ans == correct_ans: 
        total += 1 

它比以这种更紧凑但更慢的方式递增 total 快 2 倍以上:

total += int(stdnt_ans == correct_ans)