특정 인덱스의 요소가 다른 요소 목록과 같은지 확인해야 하는 경우 단순 반복 및 Boolean 값을 사용합니다.
예시
아래는 동일한 데모입니다 -
my_list_1 = [69, 96, 23, 57, 13, 75, 13]
my_list_2 = [68, 21, 69, 23, 49, 35, 73]
print("The first list is : " )
print(my_list_1)
print("The first list after sorting is :")
my_list_1.sort()
print(my_list_1)
print("The second list is : " )
print(my_list_2)
print("The first list after sorting is :")
my_list_2.sort()
print(my_list_2)
check_list = [66, 89, 69]
print("The second list is : " )
print(check_list)
print("The check list after sorting is :")
check_list.sort()
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
if(my_result == True):
print("The elements of the list are equal to the elements in the check list")
else:
print("The elements of the list aren't equal to elements in the check list") 출력
The first list is : [69, 96, 23, 57, 13, 75, 13] The first list after sorting is : [13, 13, 23, 57, 69, 75, 96] The second list is : [68, 21, 69, 23, 49, 35, 73] The first list after sorting is : [21, 23, 35, 49, 68, 69, 73] The second list is : [66, 89, 69] The check list after sorting is : [66, 69, 89] The elements of the list aren't equal to elements in the check list
설명
-
두 개의 정수 목록이 정의되어 콘솔에 표시됩니다.
-
정렬되어 콘솔에 표시됩니다.
-
부울 값이 True에 할당됩니다.
-
첫 번째 목록은 '열거'를 사용하여 반복됩니다.
-
특정 인덱스의 요소를 비교하여 세 번째 목록에서 해당 요소를 찾을 수 있는지 확인합니다.
-
찾지 못하면 Boolean 값을 'False'로 할당합니다.
-
컨트롤이 루프에서 벗어납니다.
-
Boolean 값에 따라 콘솔에 메시지가 표시됩니다.