如何检查答案是否在2D列表中

时间:2018-10-20 09:45:18

标签: python python-3.x

blueprint = [[1,"A"], [2,"C"], [3,"B"], [4,"D"], [5,"A"], [6,"A"], [7,"B"], [8,"A"], [9,"C"], [10,"A"], [11,"D"], [12,"A"], [13,"C"], [14,"C"]
         ,[15,"B"], [16,"A"], [17,"B"], [18,"A"], [19,"C"], [20,"D"]]


def check_answer(students_answer):
    points = 0
    total = 20
    if students_answer[0]==blueprint[0][1]:
        points =+ 1
    elif students_answer[1]==blueprint[1][1]:
        points =+ 1
#etc.

    else:
        points =+ 0
    score = (points*100)/(total)
    return score

print(check_answer(["A", "C"]))

为什么我的函数计算正确答案的百分比的时间比答案1(即“ A”)的时间长?

3 个答案:

答案 0 :(得分:1)

我不明白为什么您需要重新调用blueprint中的列表索引,但是如果数据是这样的,您可以将数据zip在一起,解包和比较。

这种方式实际上是无效的。如果您有100个问题怎么办?您是否会复制/粘贴100次错误的elif语句?

在反馈给sum的生成器理解中,成功的得分为1,失败的得分为0,除以总数并乘以100:

def check_answer(students_answer):
    return 100*(sum(correct==attempt for (_,correct),attempt in zip(blueprint,students_answer))/len(blueprint))

答案 1 :(得分:1)

blueprint列表中元组的第一项是多余的,因为它们只是它们各自元组的索引加一个。您应该改为使用简单的字符串列表:

blueprint = ['A', 'C', 'B', 'D', 'A', 'A', 'B', 'A', 'C', 'A', 'D', 'A', 'C', 'C', 'B', 'A', 'B', 'A', 'C', 'D']

,以便您可以像这样压缩两个列表来计算student_answer中正确答案的百分比:

sum(1 for s, b in zip(student_answer, blueprint) if s == b) / len(student_answer) * 100

答案 2 :(得分:1)

  

为什么我的函数计算正确答案的百分比的时间比答案1(即“ A”)的时间长?

让我们看看您的数据和功能

# data
blueprint = [[1,"A"], [2,"C"], [3,"B"], [4,"D"], [5,"A"], [6,"A"], [7,"B"], [8,"A"], [9,"C"], [10,"A"], [11,"D"], [12,"A"], [13,"C"], [14,"C"], [15,"B"], [16,"A"], [17,"B"], [18,"A"], [19,"C"], [20,"D"]]

# function call
print(check_answer(["A", "C"]))
blueprint中的

第一个列表是[1,"A"]check_answer()参数为["A", "C"]。当循环中的行运行时,它找到了要查找的内容

if students_answer[0]==blueprint[0][1]:    # students_answer[0] is "A", blueprint[0][1] is "A", too
    points =+ 1
elif students_answer[1]==blueprint[1][1]:
    points =+ 1
#etc.

这意味着它会跳过所有省略号和其他内容,直接计算score。这就是为什么分数仅包含前"A"的原因。

您可以使用的一种方法是使用zip(*blueprint)将蓝图中的列表解包到此

[(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20),
('A', 'C', 'B', 'D', 'A', 'A', 'B', 'A', 'C', 'A', 'D', 'A', 'C', 'C', 'B', 'A', 'B', 'A', 'C', 'D')]

然后在其上循环以计算成绩。

所以

scorelist = list(zip(*blueprint))
total = len(scorelist[1])
answer_list = ["A", "C"]
first_a, second_a = answer_list
points = 0

for sc in scorelist[1]:
    if sc == first_a or sc == second_a:
        points += 1

score = (points*100)/(total)
print(score)

或者您甚至可以加入所有乐谱字符串并使用str.count()

joined_scores = ''.join(scorelist[1])
print(joined_scores)
# 'ACBDAABACADACCBABACD'

points = joined_scores.count(first_a) + joined_scores.count(second_a)
print(points*100/total)
# 65.0