Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/310.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 将2个列表与元素的位置进行比较?_Python_List_Compare - Fatal编程技术网

Python 将2个列表与元素的位置进行比较?

Python 将2个列表与元素的位置进行比较?,python,list,compare,Python,List,Compare,我有两张单子 question = [a, b, c, d] solution = [c, b, c, a] 因此,我必须根据位置比较每个元素,并返回结果(正确或错误,并说明正确答案) 所以问题1答案=a,但解决方案=c,所以输出应该打印问题1:a,错误答案是c 如何编写显示该输出的函数?使用: 输出: >>> results [False, True, True, False] >>> results ['Q1: a, wrong answer is

我有两张单子

question = [a, b, c, d] 
solution = [c, b, c, a]
因此,我必须根据位置比较每个元素,并返回结果(正确或错误,并说明正确答案)

所以问题1答案=a,但解决方案=c,所以输出应该打印问题1:a,错误答案是c

如何编写显示该输出的函数?

使用:

输出:

>>> results
[False, True, True, False]
>>> results
['Q1: a, wrong answer is c',
 'Q2: b - correct',
 'Q3: c - correct',
 'Q4: d, wrong answer is a']
或者,对于描述性字符串,我们可以添加

输出:

>>> results
[False, True, True, False]
>>> results
['Q1: a, wrong answer is c',
 'Q2: b - correct',
 'Q3: c - correct',
 'Q4: d, wrong answer is a']

您可以使用
zip
来“粘合”正确/错误的答案,并使用
枚举
来跟踪问题的编号

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}!')       

这听起来像是一个简单的循环问题。你试过什么吗?可能迭代其中一个列表,并检查另一个列表上的相应元素?
enumerate(zip(问题,解决方案),1)
,您可以指定enumerate的开始
Q1 is wrong, answer was a but solution was c!
Q4 is wrong, answer was d but solution was a!