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

Sắp xếp trong Python: a.sort, sorted(a), np.argsort, np.lexsort


Python cung cấp nhiều cách sắp xếp: built-in sorted(), list.sort(), và NumPy argsort, lexsort cho nhu cầu nâng cao.

1. sorted(iterable) - Trả về list MỚI đã sắp xếp

a = [9,5,3,1,12,6]
b = sorted(a)
print("Sorted:", b)      # [1, 3, 5, 6, 9, 12]
print("Original:", a)    # [9, 5, 3, 1, 12, 6] - KHÔNG thay đổi

2. list.sort() - Sắp xếp IN-PLACE (sửa đổi list gốc)

a = [9,5,3,1,12,6]
print("Original:", a)
a.sort()
print("After sort():", a)  # [1, 3, 5, 6, 9, 12] - a đã thay đổi

So sánh sorted() vs sort()

Đặc điểmsorted()list.sort()
Trả vềList mớiNone
GốcGiữ nguyênBị sửa đổi
Hiệu năngChậm hơn (copy)Nhanh hơn
Áp dụngMọi iterableChỉ list

3. numpy.argsort - Trả về CHỈ SỐ (indices) của mảng đã sắp xếp

import numpy as np
x = np.array([9,5,3,1,12,6])
indices = np.argsort(x)
print("Indices:", indices)        # [3 2 1 5 0 4]
print("Sorted values:", x[indices])  # [1 3 5 6 9 12]

4. numpy.lexsort - Sắp xếp đa khóa (multi-key sort)

Sắp xếp theo key cuối cùng trước, rồi key trước đó... (giống SQL ORDER BY colA, colB).

colA = [2,5,1,8,1]  # Key chính
colB = [9,0,3,2,0]  # Key phụ
# Sắp xếp theo colA, nếu bằng thì theo colB
indices = np.lexsort((colB, colA))  # Note: (key_phụ, key_chính)
print("Indices:", indices)          # [4 2 0 1 3]
print("Pairs:", [(colA[i], colB[i]) for i in indices])
# [(1, 0), (1, 3), (2, 9), (5, 0), (8, 2)]

Khi nào dùng cái nào?

  • sorted(): Cần list mới, giữ gốc, dùng cho bất kỳ iterable nào.
  • list.sort(): Chỉ cần sắp xếp list gốc, tiết kiệm memory.
  • np.argsort: Cần index để sắp xếp mảng khác cùng cấu trúc, hoặc fancy indexing.
  • np.lexsort: Sắp xếp đa cột (multi-column sort).

Kết luận

Hiểu rõ sự khác biệt giúp chọn công cụ phù hợp: built-in cho general purpose, NumPy cho data science/multi-key sort.