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