Xóa trùng lặp từ list là thao tác thường gặp. Có nhiều phương pháp với đặc điểm khác nhau về thứ tự, hiệu năng, kiểu dữ liệu.
1. Cách cơ bản (naive) - giữ thứ tự
res = []
for x in test_list:
if x not in res:
res.append(x)2. List comprehension + kiểm tra - giữ thứ tự
res = [] [res.append(x) for x in test_list if x not in res]
3. Sử dụng set() - KHÔNG giữ thứ tự
list(set(test_list))
4. List comprehension + enumerate() - giữ thứ tự
res = [x for i, x in enumerate(test_list) if x not in test_list[:i]]
5. collections.OrderedDict.fromkeys() - giữ thứ tự (Python 3.7+ dict cũng giữ thứ tự)
from collections import OrderedDict list(OrderedDict.fromkeys(test_list)) # Python 3.7+: list(dict.fromkeys(test_list))
So sánh
| Phương pháp | Giữ thứ tự | Độ phức tạp | Ghi chú |
|---|---|---|---|
| Naive / list comp | Có | O(n²) | Chậm list lớn |
| set() | Không | O(n) | Nhanh nhất |
| enumerate | Có | O(n²) | Tương tự naive |
| OrderedDict/dict | Có | O(n) | Khuyên dùng |
Kết quả mẫu
Original: [1, 3, 5, 6, 3, 5, 6, 1] Naive: [1, 3, 5, 6] List comp: [1, 3, 5, 6] set(): [1, 3, 5, 6] (thứ tự có thể khác) enumerate: [1, 5, 3, 6] OrderedDict: [1, 3, 5, 6]