2014-06-08 73 views
0
answer_list = ['a', 'b', 'c', 'd'] 
student_answers = ['a', 'c', 'b', 'd'] 
incorrect = [] 

我想在列表1比較指數0到列表2指數0,如果他們是平等的,在移動每個列表比較索引1。比較2所列出並返回指數值第三列表

在這種情況下,list1!中的index1!= index2在列表2中,所以我想將index + 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() 
+0

你可以給一些*輸入/輸出*的例子嗎? – Christian

+0

使用[enumerate()](https://docs.python.org/2/library/functions.html#enumerate) – agconti

+0

您的代碼沒有按照您所描述的算法。你想遍歷_indices_並在每個索引處比較list1和list2,但是你的代碼循環遍歷一個列表的_values_,並且將每個值與另一個列表的每個值進行比較。 –

回答

1

您可以使用枚舉和列表理解來檢查索引比較。

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]] 
2

,你還需要遍歷那些列表同時。有多種方法可以做到這一點,這裏有一些。

內置函數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]) 

枚舉負責跟蹤索引你的,所以你不需要創建只是一個專櫃。

第三種方法是使用索引遍歷列表。要做到這一點的方法之一是寫:

for pos range(len(list1)): 
    if list1[pos] != list2[pos]: 
     incorrect.append(list2[pos]) 

注意如何使用enumerate你可以得到指標外的開箱。

所有這些方法也可以使用列表解析編寫,但在我看來,這是更具可讀性。

相關問題