我会给出具体案例和通用案例,以便帮助更多人:
我有一个有序列表列表和另一个与每个有序列表长度相同的列表。榜单中的每一个榜单都是学生一次大规模测评的答案,其次是考试的正确答案。我需要检查正确答案的百分比,也就是按顺序检查每个列表中每个项目之间的匹配项数。输出应该是一个列表,其中 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/