collections Module
collections module มี container data types ที่เพิ่มความสามารถจาก built-in types เช่น dict, list, tuple ช่วยให้โค้ดกระชับขึ้น ทำงานเร็วขึ้น และอ่านง่ายขึ้น
ทำไมต้องใช้ collections
Section titled “ทำไมต้องใช้ collections”Built-in types บางทีต้องเขียนโค้ดเยอะเกินไป collections ช่วยลดความซับซ้อน:
# ปัญหา: ต้องเช็ค key ก่อนเพิ่ม element ใน list# วิธีเดิม (ยาวและซ้ำซ้อน)d = {}for item in ['apple', 'banana', 'apple', 'cherry']: if item not in d: d[item] = 0 d[item] += 1print(f"วิธีเดิม: {d}")
# วิธีใหม่ด้วย Counter (กระชับกว่ามาก)from collections import Countercounter = Counter(['apple', 'banana', 'apple', 'cherry'])print(f"Counter: {dict(counter)}")
# อีกตัวอย่าง: groupingitems = [('fruit', 'apple'), ('vegetable', 'carrot'), ('fruit', 'banana')]
# วิธีเดิมgroups = {}for category, item in items: if category not in groups: groups[category] = [] groups[category].append(item)print(f"\nวิธีเดิม: {groups}")
# วิธีใหม่ด้วย defaultdictfrom collections import defaultdictgroups = defaultdict(list)for category, item in items: groups[category].append(item) # ไม่ต้องเช็ค key!print(f"defaultdict: {dict(groups)}")เข้าสู่ระบบเพื่อดูเนื้อหาเต็ม
ยืนยันตัวตนด้วยบัญชี Google เพื่อปลดล็อกบทความทั้งหมด
Login with Google