เมื่อจำเป็นต้องตรวจสอบว่าดัชนีขององค์ประกอบเท่ากับองค์ประกอบในรายการหรือไม่ จะใช้การวนซ้ำอย่างง่ายและแอตทริบิวต์การแจงนับ
ตัวอย่าง
ด้านล่างนี้เป็นการสาธิตสิ่งเดียวกัน -
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
-
รายการแรกจะถูกทำซ้ำโดยใช้การแจงนับและเปรียบเทียบดัชนีของสององค์ประกอบแรกของทั้งสองรายการตามลำดับ
-
หากเท่ากันและหากองค์ประกอบนี้มีอยู่ในรายการจำนวนเต็ม ค่าบูลีนจะถูกตั้งค่าเป็นเท็จ
-
ตัวควบคุมแยกออกจากลูป
-
ตามค่าบูลีน ข้อความที่เกี่ยวข้องจะแสดงบนคอนโซล