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

Python - Các cách xóa phần tử trùng lặp khỏi list


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ápGiữ thứ tựĐộ phức tạpGhi chú
Naive / list compCóO(n²)Chậm list lớn
set()KhôngO(n)Nhanh nhất
enumerateCóO(n²)Tương tự naive
OrderedDict/dictCó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]