ลิสต์เป็นคอนเทนเนอร์หลัก การลบค่าซ้ำ (Remove duplicates) มีหลายวิธี แต่ละอย่างมีคุณสมบัติต่างกัน
1. วิธีดิบ (Naive) - รักษาลำดับ
test_list = [1, 3, 5, 6, 3, 5, 6, 1]
res = []
for i in test_list:
if i not in res:
res.append(i)
# [1, 3, 5, 6]
2. List Comprehension + Side Effect - รักษาลำดับ
res = [] [res.append(x) for x in test_list if x not in res] # [1, 3, 5, 6]
3. set() - ไม่รักษาลำดับ, เร็วที่สุด
test_list = list(set(test_list)) # ผลลัพธ์ไม่คงลำดับ เช่น [1, 3, 5, 6] (ลำดับไม่แน่นอน)
4. List Comprehension + enumerate() - รักษาลำดับ
res = [i for n, i in enumerate(test_list) if i not in test_list[:n]] # [1, 3, 5, 6]
5. collections.OrderedDict.fromkeys() - รักษาลำดับ, Python 3.7+ dict ก็ได้
from collections import OrderedDict res = list(OrderedDict.fromkeys(test_list)) # Python 3.7+: list(dict.fromkeys(test_list)) # [1, 3, 5, 6]
สรุป
| วิธี | รักษาลำดับ | ความเร็ว | หมายเหตุ |
|---|---|---|---|
| Naive loop | ใช่ | ช้า O(n²) | เข้าใจง่าย |
| set() | ไม่ | เร็ว O(n) | เหมาะไม่สนลำดับ |
| dict.fromkeys() | ใช่ | เร็ว O(n) | แนะนำ Python 3.7+ |
| enumerate + slice | ใช่ | ช้า O(n²) | สั้นแต่ไม่ควรใช้ใหญ่ |