如何根据python中的正确答案按升序显示学生

时间:2019-11-21 18:29:32

标签: python

好的,所以我正在编写此代码,但不确定如何使学生以最少的顺序获得最大的正确答案。输出应为“学生3的正确答案数为4”,依此类推。 这是我当前的代码:

def main():
  answers = [
    ['A', 'B', 'A', 'C', 'C', 'D', 'E', 'E', 'A', 'D'],
    ['D', 'B', 'A', 'B', 'C', 'A', 'E', 'E', 'A', 'D'],
    ['E', 'D', 'D', 'A', 'C', 'B', 'E', 'E', 'A', 'D'],
    ['C', 'B', 'A', 'E', 'D', 'C', 'E', 'E', 'A', 'D'],
    ['A', 'B', 'D', 'C', 'C', 'D', 'E', 'E', 'A', 'D'],
    ['B', 'B', 'E', 'C', 'C', 'D', 'E', 'E', 'A', 'D'],
    ['B', 'B', 'A', 'C', 'C', 'D', 'E', 'E', 'A', 'D'],
    ['E', 'B', 'E', 'C', 'C', 'D', 'E', 'E', 'A', 'D']]
  key = ['D', 'B', 'D', 'C', 'C', 'D', 'A', 'E', 'A', 'D']
  for i in range(len(answers)):
    correctCount = 0
    for j in range(len(answers[i])):
      if answers[i][j] == key[j]:
        correctCount +=1
    print("Student", i, "'s correct count is", correctCount)
main()

1 个答案:

答案 0 :(得分:2)

我认为最好是分步骤解决问题:

  1. 确定正确答案的数量
  2. 排序输出

鉴于前面的步骤,您可以执行以下操作:

answers = [
    ['A', 'B', 'A', 'C', 'C', 'D', 'E', 'E', 'A', 'D'],
    ['D', 'B', 'A', 'B', 'C', 'A', 'E', 'E', 'A', 'D'],
    ['E', 'D', 'D', 'A', 'C', 'B', 'E', 'E', 'A', 'D'],
    ['C', 'B', 'A', 'E', 'D', 'C', 'E', 'E', 'A', 'D'],
    ['A', 'B', 'D', 'C', 'C', 'D', 'E', 'E', 'A', 'D'],
    ['B', 'B', 'E', 'C', 'C', 'D', 'E', 'E', 'A', 'D'],
    ['B', 'B', 'A', 'C', 'C', 'D', 'E', 'E', 'A', 'D'],
    ['E', 'B', 'E', 'C', 'C', 'D', 'E', 'E', 'A', 'D']]


def number_of_correct_answers(answers, golden=['D', 'B', 'D', 'C', 'C', 'D', 'A', 'E', 'A', 'D']):
    """Return the number of correct answers given a gold standard"""
    return sum(g == a for g, a in zip(golden, answers))


for student_answer in sorted(answers, key=number_of_correct_answers, reverse=True):  # the best come first
    print(student_answer, 'Number of correct', number_of_correct_answers(student_answer))

输出

['A', 'B', 'D', 'C', 'C', 'D', 'E', 'E', 'A', 'D'] Number of correct 8
['A', 'B', 'A', 'C', 'C', 'D', 'E', 'E', 'A', 'D'] Number of correct 7
['B', 'B', 'E', 'C', 'C', 'D', 'E', 'E', 'A', 'D'] Number of correct 7
['B', 'B', 'A', 'C', 'C', 'D', 'E', 'E', 'A', 'D'] Number of correct 7
['E', 'B', 'E', 'C', 'C', 'D', 'E', 'E', 'A', 'D'] Number of correct 7
['D', 'B', 'A', 'B', 'C', 'A', 'E', 'E', 'A', 'D'] Number of correct 6
['E', 'D', 'D', 'A', 'C', 'B', 'E', 'E', 'A', 'D'] Number of correct 5
['C', 'B', 'A', 'E', 'D', 'C', 'E', 'E', 'A', 'D'] Number of correct 4

以上功能的键取决于功能:sumsorted。在上面的示例中,如果您想采用其他方法,则最好的学生排在第一位,只需删除reverse=True参数。

请参阅:

  1. Sorting - HOWTO