2016-08-25 31 views
3

我需要檢查兩個列表是否有任何相同的元素,但這些相同的元素也必須在相同的索引位置。如何檢查列表元素是否在另一個列表中,但也在同一索引

我想出了一個下醜陋的解決方案:

def check_any_at_same_index(list_input_1, list_input_2): 
    # set bool value 
    check_if_any = 0 
    for index, element in enumerate(list_input_1): 
     # check if any elements are the same and also at the same index position 
     if element == list_input_2[index]: 
      check_if_any = 1 
    return check_if_any 

if __name__ == "__main__": 
    list_1 = [1, 2, 4] 
    list_2 = [2, 4, 1] 
    list_3 = [1, 3, 5] 

    # no same elements at same index 
    print check_any_at_same_index(list_1, list_2) 
    # has same element 0 
    print check_any_at_same_index(list_1, list_3) 

必須有一個更好更快的方式做到這一點,有什麼建議?

回答

5

如果您想檢查相同索引中是否有相同的項目,可以使用zip()函數和any()中的生成器表達式。

any(i == j for i, j in zip(list_input_1, list_input_2)) 

如果您想返回該項目(第一次出現),可以使用next()

next((i for i, j in zip(list_input_1, list_input_2) if i == j), None) 

如果要檢查所有你可以用一個簡單的比較:

list_input_1 == list_input_2 
+1

我認爲OP想要「全部」。 – DeepSpace

+1

是的......如果結果有[True,False,False] any給出True ...應該是全部 –

+0

任何正是我想要的,謝謝! –

相關問題