Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

Python Collections Module: Counter, namedtuple, defaultdict, ChainMap

Python มี Collection Types หลัก 4 แบบ: List, Tuple, Set, Dictionary โมดูล collections เพิ่มความสามารถด้วยโครงสร้างข้อมูลพิเศษ: Counter, namedtuple, defaultdict, ChainMap

บทนำ: Collection Types พื้นฐาน

List

ลำดับมีเรียงลำดับ แก้ไขได้ (Mutable) อ้างอิงด้วย Index อนุญาตค่าซ้ำ

sandwiches = ["Cheese", "Ham", "Tuna", "Egg Mayo"]

Tuple

ลำดับมีเรียงลำดับ ไม่แก้ไขได้ (Immutable) ใช้ Parentheses

sandwiches = ("Cheese", "Ham", "Tuna", "Egg Mayo")

Set

ไม่มีลำดับ ไม่มี Index ไม่อนุญาตค่าซ้ำ ใช้ Curly braces

sandwiches = {"Cheese", "Ham", "Tuna", "Egg Mayo"}

Dictionary

Key-Value pairs ไม่มีลำดับ แก้ไขได้ อ้างอิงด้วย Key

sandwich = {"name": "Cheese", "price": 8.95}

โมดูล collections

Import แบบเลือกฟังก์ชันที่ต้องการ:

from collections import Counter, namedtuple, defaultdict, ChainMap

1. Counter – นับจำนวนสมาชิก

Subclass ของ Dict ใช้นับ Hashable objects รับ Iterable คืน Dict {element: count}

from collections import Counter
sales = ["BLT", "Egg Mayo", "Ham", "Ham", "Ham", "Cheese", "BLT", "Cheese"]
cnt = Counter(sales)
print(cnt["BLT"])  # 2
print(cnt)         # Counter({'Ham': 3, 'BLT': 2, 'Cheese': 2, 'Egg Mayo': 1})

2. namedtuple – Tuple ที่มีชื่อฟิลด์

สร้าง Tuple แบบมีชื่อ Attribute เข้าถึงได้ด้วย Dot notation แทน Index

from collections import namedtuple
Sandwich = namedtuple("Sandwich", "name price")
s1 = Sandwich("Chicken Teriyaki", "$3.00")
print(s1.price)  # $3.00

# สร้างจาก List
s2 = Sandwich._make(["Spicy Italian", "$3.75"])
print(s2.name)   # Spicy Italian

3. defaultdict – Dictionary ที่มีค่า Default

ไม่โยน KeyError เมื่อเข้าถึง Key ที่ไม่มี จะคืนค่า Default ตาม Factory function ที่กำหนด (เช่น int, list, str)

from collections import defaultdict
dd = defaultdict(str)  # default ค่าว่าง string
dd[0] = "Ham and Cheese"
dd[1] = "BLT"
print(dd[1])  # BLT
print(dd[2])  # "" (empty string, ไม่ Error)

4. ChainMap – รวมหลาย Dictionary

รวมหลาย Dict ให้ดูเหมือน Dict เดียว ค้นหา Key จาก Dict แรกไป Dict ต่อไป อัปเดต Dict ต้นทางจะสะท้อนใน ChainMap ทันที

from collections import ChainMap
standard = {"BLT": "$3.05", "Cheese": "$2.85"}
secret = {"Steak": "$3.60", "Tuna": "$3.20"}
menu = ChainMap(standard, secret)
print(menu["BLT"])      # $3.05
print(menu["Steak"])    # $3.60

# อัปเดต standard
standard["BLT"] = "$3.10"
print(menu["BLT"])      # $3.10 (เปลี่ยนตาม)

# เพิ่ม Dictionary ใหม่เข้าไปข้างหน้า
test = {"Veggie": "$3.00"}
new_menu = menu.new_child(test)
print(new_menu["Veggie"])  # $3.00

เมธอด keys() และ values() ใช้ได้ (คืน Keys/Values ทั้งหมด)

สรุป

โมดูล collections ขยายความสามารถของ Built-in Containers ให้ทำงานกับข้อมูลได้ยืดหยุ่นและมีประสิทธิภาพมากขึ้น:

  • Counter – นับความถี่
  • namedtuple – Tuple อ่านง่าย มีชื่อฟิลด์
  • defaultdict – ป้องกัน KeyError ด้วยค่า Default
  • ChainMap – รวมหลาย Dict จัดการเป็นหน่วยเดียว