요소의 인덱스가 목록의 요소와 같은지 확인해야 하는 경우 단순 반복 및 열거 속성을 사용합니다.
예시
아래는 동일한 데모입니다 -
my_list_1 = [12, 62, 19, 79, 58, 0, 99]
my_list_2 = [12, 74, 19, 54, 58, 0, 11]
print("The first list is :")
print(my_list_1)
print("The second list is :")
print(my_list_2)
my_list_1.sort()
my_list_2.sort()
print("The first list after sorting is ")
print(my_list_1)
print("The second list after sorting is ")
print(my_list_2)
check_list = [9, 8, 2]
print("The check_list is :")
print(check_list)
my_result = True
for index, element in enumerate(my_list_1):
if my_list_1[index] != my_list_2[index] and element in check_list:
my_result = False
break
print("The result is :")
if(my_result == True):
print("The index elements is equal to the elements of the list")
else:
print("The index elements is not equal to the elements of the list") 출력
The first list is : [12, 62, 19, 79, 58, 0, 99] The second list is : [12, 74, 19, 54, 58, 0, 11] The first list after sorting is [0, 12, 19, 58, 62, 79, 99] The second list after sorting is [0, 11, 12, 19, 54, 58, 74] The check_list is : [9, 8, 2] The result is : The index elements is equal to the elements of the list
설명
-
두 개의 정수 목록이 정의되어 콘솔에 표시됩니다.
-
정렬되어 콘솔에 표시됩니다.
-
다른 정수 목록이 정의되어 콘솔에 표시됩니다.
-
값이 Boolean True로 설정됩니다.
-
첫 번째 목록은 enumerate를 사용하여 반복되고 두 개별 목록의 처음 두 요소의 인덱스가 비교됩니다.
-
동일하고 이 요소가 정수 목록에 있으면 부울 값이 False로 설정됩니다.
-
컨트롤이 루프에서 벗어납니다.
-
Boolean 값에 따라 콘솔에 해당 메시지가 표시됩니다.