บทนำ
การเรียงลำดับ list of tuples ตามเงื่อนไขเฉพาะ เช่น เรียงตาม element ที่ 2 หรือเรียงตามหลายเกณฑ์ สามารถทำได้โดยใช้เมธอด sort() หรือฟังก์ชัน sorted() พร้อมพารามิเตอร์ key ที่รับ lambda function
ตัวอย่างโค้ด
def custom_sort(tuple_list):
"""เรียงตาม element ตำแหน่งที่ 1 (index 1) จากน้อยไปมาก"""
tuple_list.sort(key=lambda x: x[1])
return tuple_list
# ข้อมูล: (ชื่อ, คะแนน)
students = [('Will', 100), ('John', 67), ('Harold', 86), ('Jane', 35)]
print("ก่อนเรียง:", students)
sorted_students = custom_sort(students)
print("หลังเรียงตามคะแนน:", sorted_students)
ผลลัพธ์
ก่อนเรียง: [('Will', 100), ('John', 67), ('Harold', 86), ('Jane', 35)]
หลังเรียงตามคะแนน: [('Jane', 35), ('John', 67), ('Harold', 86), ('Will', 100)]
คำอธิบาย
key=lambda x: x[1]บอกให้ดูค่าตำแหน่ง index 1 (คะแนน) เป็นเกณฑ์การเรียงsort()เรียงแบบ in-place (เปลี่ยนลิสต์เดิม)- ใช้
sorted()ถ้าต้องการคืนลิสต์ใหม่โดยไม่แก้ลิสต์เดิม
ตัวอย่างขั้นสูง: เรียงหลายเงื่อนไข
# เรียงตามคะแนนน้อยไปมาก ถ้าเท่ากัน เรียงตามชื่อ A-Z students.sort(key=lambda x: (x[1], x[0]))
เรียงจากมากไปน้อย (Descending)
students.sort(key=lambda x: x[1], reverse=True)