所以我有两个列表,我将一个人的答案与正确答案进行比较:
correct_answers = ['A', 'C', 'A', 'B', 'D']
user_answers = ['B', 'A', 'C', 'B', 'D']
我需要比较他们两个(不使用集合,如果可能的话)并跟踪有多少人的答案是错误的 - 在这种情况下,3
我尝试使用以下for循环来计算有多少是正确的:
correct = 0
for i in correct_answers:
for j in user_answers:
if i == j:
correct += 1
print(correct)
但是这不起作用,我不知道我需要改变什么才能使它发挥作用。
答案 0 :(得分:2)
算一下吧:
correct_answers = ['A', 'C', 'A', 'B', 'D']
user_answers = ['B', 'A', 'C', 'B', 'D']
incorrect = sum(1 if correct != user else 0
for correct, user in zip(correct_answers, user_answers))
答案 1 :(得分:2)
我责备@alecxe说服我发布这个超高效的解决方案:
from future_builtins import map # <-- Only on Python 2 to get generator based map and avoid intermediate lists; on Py3, map is already a generator
from operator import ne
numincorrect = sum(map(ne, correct_answers, user_answers))
将所有工作推送到C层(快速疯狂,模块化设置全部的初始成本;如果处理的值是Python内置类型,则不会执行字节代码,这会消除大量开销) ,并且它没有过于神秘的一线。
答案 2 :(得分:0)
较少pythonic,更通用(和可读)的解决方案也非常简单。
correct_answers = ['A', 'C', 'A', 'B', 'D']
user_answers = ['B', 'A', 'C', 'B', 'D']
incorrect = 0
for i in range(len(correct_answers)):
if correct_answers[i] != user_answers[i]:
incorrect += 1
这假定您的列表长度相同。如果需要验证,可以在运行此代码之前执行此操作。
编辑:如果您熟悉zip
,以下代码会执行相同的操作correct_answers = ['A', 'C', 'A', 'B', 'D']
user_answers = ['B', 'A', 'C', 'B', 'D']
incorrect = 0
for answer_tuple in zip(correct_answers, user_answers):
if answer_tuple[0] != answer_tuple[1]:
incorrect += 1