我有 2 个列表
question = [a, b, c, d]
solution = [c, b, c, a]
所以我必须根据位置比较每个单独的元素并返回结果(正确或错误并陈述正确答案(
所以问题 1 答案 = a 但解决方案 = c 所以输出应该打印 Q 1:a,错误答案是 c
如何编写将显示该输出的函数?
使用zip()
:
question = ['a', 'b', 'c', 'd']
solution = ['c', 'b', 'c', 'a']
results = [x == y for x, y in zip(question, solution)]
输出:
>>> results
[False, True, True, False]
或者,对于描述性字符串,我们可以添加enumerate()
results = [f"Q{i}: {a[0]}, wrong answer is {a[1]}" if a[0] != a[1] else f"Q{i}: {a[0]} - correct" for i, a in enumerate(zip(question, solution), 1)]
输出:
>>> results
['Q1: a, wrong answer is c',
'Q2: b - correct',
'Q3: c - correct',
'Q4: d, wrong answer is a']
您可以使用zip
来"粘合"正确/错误的答案,enumerate
来跟踪问题的数量。
question = ['a', 'b', 'c', 'd']
solution = ['c', 'b', 'c', 'a']
for ix, (q, s), in enumerate(zip(question, solution), 1):
if q != s:
print(f'Q{ix} is wrong, answer was {q} but solution was {s}!')
Q1 is wrong, answer was a but solution was c!
Q4 is wrong, answer was d but solution was a!