โดยปกติเราต้องการหาดัชนีของค่าที่ต้องการ มีหลายวิธี เช่นใช้ index() แต่บางครั้งต้องการหา ดัชนีทั้งหมด ของค่าที่ซ้ำกันในลิสต์
ตัวอย่างโค้ด
1. ใช้ filter() กับ lambda
test_list = [1, 3, 4, 3, 6, 7]
print("Original list :", str(test_list))
# ใช้ filter() หาดัชนีของค่า 3
res_list = list(filter(lambda x: test_list[x] == 3, range(len(test_list))))
print("New indices list :", str(res_list))
2. ใช้ enumerate() (แนะนำ - อ่านง่ายและมีประสิทธิภาพ)
test_list = [1, 3, 4, 3, 6, 7]
print("Original list :", str(test_list))
# ใช้ enumerate()
res_list = [i for i, value in enumerate(test_list) if value == 3]
print("New indices list :", str(res_list))
3. ใช้ List Comprehension แบบดัชนี
test_list = [1, 3, 4, 3, 6, 7]
print("Original list :", str(test_list))
res_list = [i for i in range(len(test_list)) if test_list[i] == 3]
print("New indices list :", str(res_list))
4. ใช้ Naive Method (Loop ทั่วไป)
test_list = [1, 3, 4, 3, 6, 7]
print("Original list :", str(test_list))
res_list = []
for i in range(0, len(test_list)):
if test_list[i] == 3:
res_list.append(i)
print("New indices list :", str(res_list))
ผลลัพธ์
Original list : [1, 3, 4, 3, 6, 7]
New indices list : [1, 3]
สรุปและแนะนำ
- enumerate() - **แนะนำมากที่สุด** อ่านง่าย ประสิทธิภาพดี Pythonic
- List Comprehension แบบดัชนี - ทำงานได้ดี แต่อ่านยากกว่า enumerate
- filter() - Functional style แต่ช้ากว่าและอ่านยากกว่า
- Naive loop - เข้าใจง่ายสำหรับมือใหม่ แต่โค้ดยาว
กรณีต้องการแค่ดัชนีแรก
# ใช้ index() - คืนดัชนีแรกเท่านั้น โยน ValueError ถ้าไม่เจอ
idx = test_list.index(3) # 1
# ใช้ next() กับ enumerate - ปลอดภัยกว่า
idx = next((i for i, v in enumerate(test_list) if v == 3), None)