บทนำ
การเรียงลำดับลิสต์ของ tuples ตาม element ตำแหน่งที่ 2 (index 1) ใช้ sorted() พร้อม key=lambda x: x[1]
ตัวอย่างโค้ด
def sort_by_second_item(tuple_list):
return sorted(tuple_list, key=lambda x: x[1])
# ข้อมูล: (ชื่อ, อายุ)
people = [('bill', 11), ('rick', 45), ('john', 89), ('liv', 25)]
print("ก่อนเรียง:", people)
sorted_people = sort_by_second_item(people)
print("หลังเรียงตามอายุ:", sorted_people)
ผลลัพธ์
ก่อนเรียง: [('bill', 11), ('rick', 45), ('john', 89), ('liv', 25)]
หลังเรียงตามอายุ: [('bill', 11), ('liv', 25), ('rick', 45), ('john', 89)]
คำอธิบาย
key=lambda x: x[1]บอก sorted ให้ดู element index 1 (อายุ)sorted()คืนลิสต์ใหม่ ไม่เปลี่ยนลิสต์เดิม- Stable sort: ถ้าอายุเท่ากัน จะคงลำดับเดิม
ตัวเลือกเพิ่มเติม
# เรียงจากมากไปน้อย sorted(people, key=lambda x: x[1], reverse=True) # เรียงหลายเงื่อนไข: อายุ แล้วชื่อ sorted(people, key=lambda x: (x[1], x[0])) # ใช้ itemgetter (เร็วกว่า lambda เล็กน้อย) from operator import itemgetter sorted(people, key=itemgetter(1))