โจทย์: หาดัชนีของ sublist ที่มีสมาชิกตามที่ต้องการ
Input/Output
nested_list = [[1, 2, 3], [4, 5], [6, 7, 8, 9]] # ค้นหา 7, 5, 3 Output: Index of 7: 2 Index of 5: 1 Index of 3: 0
วิธีแก้: Nested Loop พร้อม Flag
nested_list = [[1, 2, 3], [4, 5], [6, 7, 8, 9]]
def find_index(element):
is_found = False
for i in range(len(nested_list)):
for j in range(len(nested_list[i])):
if nested_list[i][j] == element:
print(f'Index of {element}: {i}')
is_found = True
break
if is_found:
break
if not is_found:
print("Element is not present in the list")
find_index(7)
find_index(5)
find_index(3)
ผลลัพธ์
Index of 7: 2 Index of 5: 1 Index of 3: 0
การปรับปรุง: หากต้องการคืนค่า index แทน print ให้ return i แทน และ raise exception หรือ return -1 หากไม่เจอ
def find_sublist_index(nested_list, target):
for i, sublist in enumerate(nested_list):
if target in sublist:
return i
return -1 # หรือ raise ValueError