Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Sắp xếp list theo độ dài phần tử trong Python

Sắp xếp list chuỗi theo độ dài (length) tăng dần. Sử dụng sorted() hoặc list.sort() với tham số key=len.

Ví dụ

Input: ["hafeez", "aslan", "honey", "appi"]
Output: ["appi", "aslan", "honey", "hafeez"]  # độ dài: 4,5,5,6

Cách 1: sorted() - trả về list mới

strings = ["hafeez", "aslan", "honey", "appi"]
sorted_list = sorted(strings, key=len)
print(sorted_list)

Kết quả

['appi', 'aslan', 'honey', 'hafeez']

Cách 2: list.sort() - sắp xếp tại chỗ (in-place)

strings = ["hafeez", "aslan", "honey", "appi"]
strings.sort(key=len)
print(strings)

Kết quả

['appi', 'aslan', 'honey', 'hafeez']

Key function tùy chỉnh

# Sắp xếp theo độ dài, nếu bằng nhau thì theo alphabet
strings.sort(key=lambda s: (len(s), s))

# Sắp xếp giảm dần độ dài
strings.sort(key=len, reverse=True)
# ['hafeez', 'aslan', 'honey', 'appi']

Độ phức tạp

  • Time: O(N log N) so sánh, mỗi so sánh O(1) vì key=len trả về int đã tính.
  • Space: O(N) cho sorted(), O(1) thêm cho sort() (in-place).
  • Python Timsort ổn định (stable): phần tử bằng key giữ thứ tự gốc.

Kết luận

key=len là cách chuẩn, pythonic để sort theo độ dài. Dùng sorted() khi cần giữ list gốc, sort() khi muốn tiết kiệm bộ nhớ. Kết hợp tuple key cho tie-breaking.