比较两个列表并将索引和值返回到第三个列表
answer_list = ['a', 'b', 'c', 'd']
student_answers = ['a', 'c', 'b', 'd']
incorrect = []
我想把list1的第0个位置和list2的第0个位置进行比较,如果它们相等,就继续比较每个列表的第1个位置。
在这个例子中,list1的第1个位置和list2的第1个位置不相等,所以我想把下一个位置的索引和错误的学生答案(在这个例子中是字母c)添加到一个空列表里。这是我尝试过的,但没有成功。
def main():
list1 = ['a', 'b', 'c', 'd']
list2 = ['a', 'c', 'b', 'd']
incorrect = []
for x in list1:
for y in list2:
if x != y:
incorrect.append(y)
print(incorrect)
main()
2 个回答
3
你可以用枚举(enumerate)和列表推导(list comprehension)来检查索引的比较。
answer_list = ['a', 'b', 'c', 'd']
student_answers = ['a', 'c', 'b', 'd']
incorrect = [y for x,y in enumerate(answer_list) if y != student_answers[x]]
incorrect
['b', 'c']
如果你想找出不匹配的索引和对应的值:
incorrect = [[y,answer_list.index(y)] for x,y in enumerate(answer_list) if y != student_answers[x]]
[['b', 1], ['c', 2]]
在 x,y in enumerate(answer_list)
这段代码中,x
是元素的索引,y
是元素本身。所以,检查 if y != student_answers[x]
就是在比较两个列表中相同索引的元素。如果它们不相等,就把这个元素 y
加入到我们的列表中。
使用一个类似你自己写的循环:
def main():
list1 = ['a', 'b', 'c', 'd']
list2 = ['a', 'c', 'b', 'd']
incorrect = []
for x,y in enumerate(list1):
if list2[x] != y:
incorrect.append(y)
print(incorrect)
In [20]: main()
['b', 'c']
要获取元素和索引:
def main():
list1 = ['a', 'b', 'c', 'd']
list2 = ['a', 'c', 'b', 'd']
incorrect = []
for x,y in enumerate(list1):
if list2[x] != y:
incorrect.append([y,list1.index(y)])
print(incorrect)
In [2]: main()
[['b', 1], ['c', 2]]
4
因为你需要逐个比较列表中的元素,所以你也需要同时遍历这些列表。有好几种方法可以做到这一点,下面介绍几种。
内置的 zip 函数可以让你同时遍历多个可迭代对象。我个人觉得这是最简单、最易读的方法,可以一次性遍历多个序列。
for x,y in zip(list1, list2):
if x != y:
incorrect.append(y)
另一种方法是使用 enumerate:
for pos, value in enumerate(list1):
if value != list2[pos]:
incorrect.append(list2[pos])
使用 enumerate 可以自动帮你跟踪索引,所以你不需要专门创建一个计数器来处理这个问题。
第三种方法是通过索引来遍历列表。你可以这样写:
for pos range(len(list1)):
if list1[pos] != list2[pos]:
incorrect.append(list2[pos])
注意,使用 enumerate
时,你可以直接获取索引。
所有这些方法也可以用列表推导式来写,但我觉得这样写更容易理解。