繁体   English   中英

将 2 个列表与 ref 比较到元素的位置? [关闭]

[英]Comparing 2 lists with ref to position of element? [closed]

我有 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!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM