ในบทช่วยสอนนี้ เราจะเรียงลำดับ List ของ Tuple ตาม index ที่กำหนด (nth index) เช่น [(2, 2), (1, 2), (3, 1)] เรียงตาม index 0 → [(1, 2), (2, 2), (3, 1)]
อัลกอริทึม
1. กำหนด list of tuples และ key (index) 2. สร้างฟังก์ชันคืนค่า key-th element ของ tuple 3. ใช้ sorted(list, key=function) 4. พิมพ์ผลลัพธ์
โค้ดตัวอย่าง
tuples = [(2, 2), (1, 2), (3, 1)]
key = 0
def k_th_index(one_tuple):
return one_tuple[key]
sorted_tuples = sorted(tuples, key=k_th_index)
print(sorted_tuples)ผลลัพธ์
[(1, 2), (2, 2), (3, 1)]
กรณี Index Out of Range
key = 2 # tuple มีแค่ index 0, 1 sorted(tuples, key=k_th_index)
ผลลัพธ์
IndexError: tuple index out of range
ใช้ Lambda แทน Function แบบเต็ม
sorted_tuples = sorted(tuples, key=lambda x: x[key])
เรียงจากมากไปน้อย (Descending)
sorted_tuples = sorted(tuples, key=lambda x: x[key], reverse=True)
สรุป
ใช้ sorted() ร่วมกับ key parameter (function หรือ lambda) เพื่อเรียง tuple ตาม index ที่ต้องการ ต้องระวัง index out of range หากมีข้อสงสัย สามารถถามได้ในส่วนความคิดเห็น