Skip to main content
 首页 » 编程设计

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

2025年05月04日13webabcd

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

我想比较列表 1 中的索引 0 和列表 2 中的索引 0,如果它们相等,则移动到比较每个列表中的索引 1。

在此实例中,列表 1 中的索引 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() 

请您参考如下方法:

由于您需要逐个元素地比较列表,因此您还需要同时迭代这些列表。有不止一种方法可以做到这一点,这里有一些。

内置函数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 获取开箱即用的索引。

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