Trong hướng dẫn này, chúng ta tìm hiểu hàm sorted() trong Python.
Hàm sorted() sắp xếp iterable theo thứ tự tăng dần hoặc giảm dần. Có thể sắp xếp list of dictionaries theo key/value khác nhau. sorted() KHÔNG phải thuật toán in-place như phương thức sort().
sorted() mặc định
Sắp xếp tăng dần mặc định.
Ví dụ
numbers = [4, 3, 5, 1, 2] sorted_numbers = sorted(numbers) print(sorted_numbers)
Kết quả
[1, 2, 3, 4, 5]
sorted() giảm dần
Tham số reverse=True.
Ví dụ
numbers = [4, 3, 5, 1, 2] sorted_numbers = sorted(numbers, reverse=True) print(sorted_numbers)
Kết quả
[5, 4, 3, 2, 1]
Tham số key với sorted()
Tham số key cho biết sắp xếp dựa trên giá trị nào. Dùng lambda để trích xuất giá trị từ dict.
Ví dụ
numbers = [{'a': 5}, {'b': 1, 'a': 1}, {'c': 3, 'a': 3}, {'d': 4, 'a': 4}, {'e': 2, 'a': 2}]
sorted_dictionaries = sorted(numbers, key=lambda d: d['a'])
print(sorted_dictionaries)
Kết quả
[{'b': 1, 'a': 1}, {'e': 2, 'a': 2}, {'c': 3, 'a': 3}, {'d': 4, 'a': 4}, {'a': 5}]
Kết luận
sorted() trả về list mới đã sắp xếp, hỗ trợ reverse và key tùy chỉnh. Hãy bình luận nếu có thắc mắc.