ในบทช่วยสอนนี้ เราจะเขียนโปรแกรมที่ค้นหาดัชนีขององค์ประกอบย่อยจากรายการ มาดูตัวอย่างให้เข้าใจกันชัดๆ
อินพุต
nested_list = [[1, 2, 3], [4, 5], [6, 7, 8, 9]]
ผลลัพธ์
Index of 7:- 2 Index of 5:- 1 Index of 3:- 0
มาดูวิธีที่ง่ายและธรรมดาที่สุดในการแก้ปัญหาที่กำหนดกัน ทำตามขั้นตอนที่กำหนด
- เริ่มต้นรายการ
- วนซ้ำรายการโดยใช้ดัชนี
- วนซ้ำในรายการย่อยและตรวจสอบองค์ประกอบที่คุณต้องการค้นหาดัชนี
- ถ้าเราพบองค์ประกอบแล้วพิมพ์และทำลายมัน
ตัวอย่าง
# initializing the lit
nested_list = [[1, 2, 3], [4, 5], [6, 7, 8, 9]]
# function to find the index
def index(element):
# initializing a flag for tracking the element
is_found = False
# iterating over the list
for i in range(len(nested_list)):
# iterating over the sub list
for j in range(len(nested_list[i])):
# cheking for the element
if nested_list[i][j] == element:
# printing the sub list index that contains the element
print(f'Index of {element}: {i}')
# changing the flag to True
is_found = True
# breaking the inner loop
break
# breaking the outer loop
if is_found:
break
# checking whether the element is found or not
if not is_found:
# printing the element not found message
print("Element is not present in the list")
index(7)
index(5)
index(3) ผลลัพธ์
หากคุณเรียกใช้โค้ดด้านบน คุณจะได้ผลลัพธ์ดังต่อไปนี้
Index of 7: 2 Index of 5: 1 Index of 3: 0
บทสรุป
หากคุณมีคำถามใด ๆ เกี่ยวกับบทช่วยสอน โปรดระบุในส่วนความคิดเห็น