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

Python – Sắp xếp list theo chữ số (Sort List items on basis of their Digits)

Khi cần sắp xếp list số nguyên dựa trên giá trị chữ số (digit-by-digit), ta dùng sorted(), lambda, ljust và padding.

Ví dụ

my_list = [4344, 2611, 122, 541, 33, 892, 48292, 460, 390, 120, 10, 2909, 11239, 1]
print("List gốc:")
print(my_list)

print("Sau sắp xếp thường:")
my_list.sort()
print(my_list)

my_temp_val = map(str, my_list)
my_max_length = max(map(len, my_temp_val))

my_result = sorted(my_list, key=lambda index: (str(index).ljust(my_max_length, 'a')))

print("Kết quả sắp xếp theo chữ số:")
print(my_result)

Kết quả đầu ra

List gốc:
[4344, 2611, 122, 541, 33, 892, 48292, 460, 390, 120, 10, 2909, 11239, 1]
Sau sắp xếp thường:
[1, 10, 33, 120, 122, 390, 460, 541, 892, 2611, 2909, 4344, 11239, 48292]
Kết quả sắp xếp theo chữ số:
[10, 11239, 120, 122, 1, 2611, 2909, 33, 390, 4344, 460, 48292, 541, 892]

Giải thích

  • Chuyển số thành string, tìm độ dài max (5: 48292, 11239).
  • ljust(5, 'a') pad bên phải bằng 'a': "1"→"1aaaa", "10"→"10aaa", "11239"→"11239".
  • Sắp xếp lexicographic (theo từ điển) trên chuỗi đã pad.
  • '1aaaa' < '10aaa' < '11239' < '120aa' < '122aa' < '2611a'...
  • Kết quả: 10, 11239, 120, 122, 1, 2611, 2909, 33, 390, 4344, 460, 48292, 541, 892.

Ý nghĩa: Sắp xếp "theo chữ số" (digit-wise) thay vì giá trị số học. 10 < 1 vì '1'<'1' rồi '0'<'a'.

Cách khác: sorted(my_list, key=lambda x: str(x).zfill(max_len)) pad '0' bên trái.