比较2个列表并将索引和值返回到第三个列表

时间:2014-06-08 22:50:36

标签: python list

answer_list = ['a', 'b', 'c', 'd']
student_answers = ['a', 'c', 'b', 'd']
incorrect = []

我想将list1中的索引0与list2中的索引0进行比较,如果它们相等,则移动到比较每个列表中的索引1。

在这个实例中,list1中的索引1!=列表2中的索引1所以我想将索引+ 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 个答案:

答案 0 :(得分: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,您可以获得开箱即用的索引。

所有这些方法也可以使用列表推导来编写,但在我看来,这更具可读性。

答案 1 :(得分:2)

您可以使用枚举和列表推导来检查索引比较。

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]]
相关问题