2016-08-25 3 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]가있는 경우 True를 지정하면 ... 모두 –

+0

이되어야합니다. –

관련 문제