Khi cần sắp xếp danh sách tuple theo cách tùy chỉnh, phương thức sort() (in-place) hoặc hàm sorted() (trả về list mới) có thể dùng với tham số key.
Tham số key nhận một hàm để trích xuất khóa so sánh từ mỗi phần tử.
Hàm lambda thường dùng để định nghĩa hàm key ngắn gọn.
Ví dụ
def custom_sort(tuple_list):
"""
Sắp xếp list of tuples theo phần tử thứ 2 (index 1) tăng dần.
Sử dụng sort() in-place.
"""
tuple_list.sort(key=lambda x: x[1])
return tuple_list
# Danh sách tuple: (tên, điểm)
my_tuples = [('Will', 100), ('John', 67), ('Harold', 86), ('Jane', 35)]
print("Danh sách ban đầu:")
print(my_tuples)
print("\nĐang sắp xếp theo điểm (phần tử index 1)...")
sorted_list = custom_sort(my_tuples)
print("Kết quả sau sắp xếp:")
print(sorted_list)
Kết quả
Danh sách ban đầu:
[('Will', 100), ('John', 67), ('Harold', 86), ('Jane', 35)]
Đang sắp xếp theo điểm (phần tử index 1)...
Kết quả sau sắp xếp:
[('Jane', 35), ('John', 67), ('Harold', 86), ('Will', 100)]
Giải thích
- Hàm
custom_sortnhận list of tuples. sort(key=lambda x: x[1])sắp xếp dựa trên phần tử thứ 2 (index 1) của mỗi tuple.lambda x: x[1]trả về phần tử index 1 làm khóa so sánh.sort()sắp xếp in-place (thay đổi list gốc) và trả vềNone, nên hàm return list đã sửa đổi.
Các biến thể sắp xếp tùy chỉnh
# Sắp xếp giảm dần theo phần tử thứ 2 my_tuples.sort(key=lambda x: x[1], reverse=True) # Sắp xếp theo nhiều tiêu chí: trước theo điểm, sau theo tên my_tuples.sort(key=lambda x: (x[1], x[0])) # Sắp xếp theo tổng các phần tử trong tuple my_tuples.sort(key=lambda x: sum(x)) # Dùng sorted() để không thay đổi list gốc new_sorted = sorted(my_tuples, key=lambda x: x[1]) # Sắp xếp tuple của tuple (nested tuple) nested = ((3, 1), (1, 2), (2, 0)) sorted_nested = tuple(sorted(nested, key=lambda x: x[1]))
Toán tử itemgetter (hiệu quả hơn lambda)
from operator import itemgetter # itemgetter(1) nhanh hơn lambda x: x[1] my_tuples.sort(key=itemgetter(1)) # Lấy nhiều index: itemgetter(1, 0) tương đương lambda x: (x[1], x[0])