【问题标题】:comparing each element in a string with another string at the same position将字符串中的每个元素与同一位置的另一个字符串进行比较
【发布时间】:2015-05-25 06:22:17
【问题描述】:

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

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

【问题讨论】:

    标签: python string loops python-3.x compare


    【解决方案1】:

    任何时候您的问题以“在同一位置的另一个___”结尾,答案几乎总是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]
    

    【讨论】:

      【解决方案2】:

      您可以使用distance 包 - 它提供了一个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]
      

      【讨论】:

      • 谢谢,但很遗憾,我们不允许导入任何内容。
      • @Moh'dH 在这种情况下,使用 abarnert 的答案
      猜你喜欢
      • 2020-09-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多