将字符串中的每个元素与同一位置的另一个字符串进行比较

comparing each element in a string with another string at the same position

我想将学生的答案与标准答案进行比较。学生进行多项选择题测试。一共有5道题,每道题有3道选择题。 学生为所有问题选择以下选项:“12231”。例如:对于 Q(1):学生选择选项“1”,对于 Q(2):学生选择选项“2”……等等。 现在,我需要通过将学生的总分与模型答案进行比较来计算学生的总分:“12132”。这名学生获得了 3/5 分。 学生的答案将始终与模型答案一样长。例如学生不会跳过任何问题。

我需要做完全相同的事情,但有数百名学生。我可以用代码来做吗?我只能想到使用 for 循环并迭代学生的答案,但我想不出一种方法来比较两者并计算学生的分数。

任何时候你的问题以 "in another ___ at the same position" 结尾,答案几乎总是 zip

如果您 zip 将两个字符串(例如学生的答案和答案键)放在一起,您会得到一个可迭代的对:学生的第一个答案和答案键的第一个答案,然后是两个第二个答案,然后等等。

因此,如果您想计算学生答对了多少答案,只需使用 for 语句或推导式遍历 zip。例如:

score = sum(student==correct for student, correct in zip(student_answers, answer_key))

这使用了一个额外的小技巧:如果您对一堆布尔值求和,则 True 值计为 1,False 值计为 0。但除此之外,除了循环 zip.

如果您想对学生列表中每个学生的答案都执行此操作,那只是围绕此问题的另一个循环。例如:

all_student_scores = []
for student_answers in all_student_answers:
    score = sum(student==correct for student, correct in zip(student_answers, answer_key)
    all_student_scores.append(score)

或者,如果您想超级简洁:

all_student_scores = [sum(student==correct for student, correct in zip(student_answers, answer_key)
                      for student_answers in all_student_answers]

您可以使用distance package - it provides a hamming distance计算器:

import distance
distance.hamming("12231", "22131")

现在,如果您有学生答案列表 (str) 和模型,您可以:

def score(student_answers,model):
    return len(model)-[distance.hamming(ans,model) for ans in student_answers]