Khi cần sắp xếp list of tuples dựa trên phần tử thứ 2 (index 1) của mỗi tuple, dùng sorted() hoặc list.sort() với tham số key.
Hàm lambda x: x[1] trích xuất phần tử index 1 làm khóa sắp xếp.
Ví dụ
def sort_by_second_item(tuple_list):
"""Sắp xếp list of tuples theo phần tử thứ 2 (index 1) tăng dần."""
return sorted(tuple_list, key=lambda x: x[1])
# Dữ liệu: (tên, giá trị)
data = [('bill', 11), ('rick', 45), ('john', 89), ('liv', 25)]
print("Danh sách gốc:")
for item in data:
print(f" {item}")
sorted_data = sort_by_second_item(data)
print("\nSau khi sắp xếp theo giá trị (index 1):")
for item in sorted_data:
print(f" {item}")
Kết quả
Danh sách gốc:
('bill', 11)
('rick', 45)
('john', 89)
('liv', 25)
Sau khi sắp xếp theo giá trị (index 1):
('bill', 11)
('liv', 25)
('rick', 45)
('john', 89)
Giải thích
sorted(data, key=lambda x: x[1])tạo list MỚI đã sắp xếp.lambda x: x[1]trả về phần tử index 1 của mỗi tuple.sortedsử dụng Timsort (ổn định - stable), giữ thứ tự tương đối cho key bằng nhau.- List gốc
datakhông bị thay đổi.
Sắp xếp giảm dần
# reverse=True
sorted_desc = sorted(data, key=lambda x: x[1], reverse=True)
print(sorted_desc)
# [('john', 89), ('rick', 45), ('liv', 25), ('bill', 11)]
In-place sort (sửa đổi list gốc)
data.sort(key=lambda x: x[1]) print(data) # List gốc đã bị sắp xếp
Sắp xếp theo nhiều tiêu chí (multi-key)
# (name, score, age)
students = [
('Alice', 85, 20),
('Bob', 90, 19),
('Charlie', 85, 21),
('Diana', 90, 20),
]
# Sắp xếp: score giảm dần, tuổi tăng dần, tên tăng dần
sorted_students = sorted(students, key=lambda x: (-x[1], x[2], x[0]))
for s in sorted_students:
print(s)
# ('Bob', 90, 19)
# ('Diana', 90, 20)
# ('Alice', 85, 20)
# ('Charlie', 85, 21)
Dùng operator.itemgetter (nhanh hơn lambda)
from operator import itemgetter # itemgetter(1) tương đương lambda x: x[1] sorted_data = sorted(data, key=itemgetter(1)) # Multi-key: itemgetter(1, 2) -> (x[1], x[2]) sorted_multi = sorted(students, key=itemgetter(1, 2))
Sắp xếp tuple của tuple (nested)
nested = ((3, 1), (1, 2), (2, 0)) # Sắp xếp theo phần tử thứ 2 của tuple con sorted_nested = tuple(sorted(nested, key=itemgetter(1))) print(sorted_nested) # ((2, 0), (3, 1), (1, 2))