python - 检查两个有序列表的匹配

标签 python list numpy

我会给出具体案例和通用案例,以便帮助更多人:

我有一个有序列表列表和另一个与每个有序列表长度相同的列表。榜单中的每一个榜单都是学生一次大规模测评的答案,其次是考试的正确答案。我需要检查正确答案的百分比,也就是按顺序检查每个列表中每个项目之间的匹配项数。输出应该是一个列表,其中 1 表示有匹配项,0 表示没有匹配项。

例子:

list1 = [['A', 'B', 'C', 'A'], ['A', 'C', 'C', 'B']]
list2 = ['A', 'B', 'C', 'A']
result = [[1, 1, 1, 1],[1, 0, 1, 0]

谢谢!

最佳答案

其他人已经做了很好的工作,详细说明了如何使用列表推导来做到这一点。以下代码是获得相同答案的初学者友好的方式。

final = []

# Begin looping through each list within list1
for test in list1:

    # Create a list to store each students scores within
    student = []
    for student_ans, correct_ans in zip(test, list2):

        # if student_ans == correct_ans at the same index...
        if student_ans == correct_ans:
            student.append(1)
        else:
            student.append(0)
    
    # Append the student list to the final list
    final.append(student)

关于python - 检查两个有序列表的匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73820799/

相关文章:

使用带有 gcc 和自排序列表的 .h 文件进行编译

python - 检查文本文件中的列表是否已存在并向其追加

python - Numpy 多维子集

python - 关于在 python 脚本中导入 psutil 的问题

python - 如何使用 Altair 为区域着色

python - 将递归解决方案写入列表

python - numpy ndarray 的解释

python - 如何使用掩码在多个维度中替换 python numpy 数组中的值?

python - tilestache Provider() 图层对象?可以获取引用URL吗?

python - 如何使用 models.FileField 将文件保存在数据库中而不是上传到服务器媒体文件夹中?