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

Python Sets: คู่มือครบวงจร Unique, Immutable Items, Set Operations

Set ใน Python เป็น Collection ของ Unique และ Immutable Objects ไม่มี Order (Unordered) ใช้ Curly Braces {}

1. สร้าง Set

# Literal
colors = {"red", "green", "blue"}
print(colors)  # {'red', 'blue', 'green'} - Order ไม่คงที่

# Constructor
colors = set(["red", "green", "blue", "red"])  # {'red', 'blue', 'green'} - Duplicate ถูกลบ

# Empty Set - ต้องใช้ set() ไม่ใช่ {} (นั่นคือ Empty Dict)
empty_set = set()

# Mixed Types
mixed = {'one', True, 13, 2.0}  # ✅ ได้

2. เข้าถึง Items (ไม่มี Index!)

colors = {"red", "green", "blue"}

# ❌ colors[0]  - Error: 'set' object is not subscriptable

# ✅ ใช้ For Loop
for color in colors:
    print(color)

# ✅ Membership Test
"red" in colors      # True
"yellow" in colors   # False

3. เพิ่ม Items

colors = {"red", "green", "blue"}

# add() - เพิ่ม 1 Item
colors.add("yellow")
# {'red', 'blue', 'green', 'yellow'}

# update() - เพิ่มหลาย Item (Iterable)
colors.update(["orange", "white", "purple"])
colors.update({"pink", "brown"})  # Set ก็ได้
# {'white', 'red', 'green', 'yellow', 'orange', 'blue', 'purple', 'pink', 'brown'}

4. ลบ Items

colors = {"red", "green", "blue", "orange"}

# remove() - ลบ Item ที่ระบุ, Error ถ้าไม่มี
colors.remove("orange")
# {'red', 'blue', 'green'}

# discard() - ลบ Item ที่ระบุ, ไม่ Error ถ้าไม่มี ✅ Safe
colors.discard("purple")  # ไม่ Error

# pop() - ลบและคืนค่า Random Item (Set ไม่มี Order)
item = colors.pop()
print(item)  # Random

# clear() - ลบทั้งหมด
colors.clear()  # set()

5. ลบ Set ทั้งตัว

colors = {"red", "green", "blue"}
del colors
# print(colors)  # NameError

6. ความยาว Set

len({"red", "green", "blue", "orange"})  # 4

7. Set Operations (คณิตศาสตร์เซต)

a = {1, 2, 3, 4}
b = {3, 4, 5, 6}

# Union (รวม) - |
a | b                    # {1, 2, 3, 4, 5, 6}
a.union(b)               # {1, 2, 3, 4, 5, 6}

# Intersection (ส่วนที่ซ้อน) - &
a & b                    # {3, 4}
a.intersection(b)        # {3, 4}

# Difference (อยู่ a ไม่อยู่ b) - -
a - b                    # {1, 2}
a.difference(b)          # {1, 2}

# Symmetric Difference (อยู่ฝั่งเดียว) - ^
a ^ b                    # {1, 2, 5, 6}
a.symmetric_difference(b) # {1, 2, 5, 6}

# Subset / Superset
{1, 2} <= a     # True (Subset)
{1, 2} < a      # True (Proper Subset)
a >= {1, 2}     # True (Superset)

8. Frozenset (Immutable Set)

# Immutable Set - ใช้เป็น Key ของ Dict ได้
fs = frozenset([1, 2, 3, 4])
d = {fs: "value"}  # ✅ ได้

# fs.add(5)  # ❌ AttributeError

9. Set Comprehension

# Unique Squares
{x**2 for x in range(-5, 6)}  # {0, 1, 4, 9, 16, 25}

# Filter
{x for x in "hello world" if x not in "aeiou"}  # {'h', 'l', ' ', 'w', 'r', 'd'}

เมื่อไหร่ควรใช้ Set?

  • ✅ ต้องการ Unique Values (ลบ Duplicate)
  • ✅ Membership Test บ่อย (O(1) vs List O(n))
  • ✅ Set Operations (Union, Intersection, Difference)
  • ✅ ต้องการ Key ของ Dict ที่เป็น Collection
  • ❌ ต้องการ Order / Index Access
  • ❌ ต้องการ Duplicate Values

บทความเกี่ยวข้อง