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

frozenset() trong Python: Set bất biến (immutable)

frozenset() tạo một set bất biến (immutable) từ iterable. Khác với set thông thường, frozenset không thể thêm/xóa/sửa phần tử sau khi tạo.

Cú pháp

frozenset(iterable)

Ví dụ: Chuyển list mutable → frozenset immutable

# List thông thường (mutable)
days = ["Mon", "Tue", "Wed", "Thu"]
days[2] = "Fri"
print("List sau thay đổi:", days)  # ['Mon', 'Tue', 'Fri', 'Thu']

# Chuyển sang frozenset
fixed_days = frozenset(days)
print("Frozenset:", fixed_days)  # frozenset({'Thu', 'Mon', 'Fri', 'Tue'})

# Thử thay đổi → LỖI
try:
    fixed_days[2] = "Wed"
except TypeError as e:
    print(f"Lỗi: {e}")  # 'frozenset' object does not support item assignment

Kết quả

List sau thay đổi: ['Mon', 'Tue', 'Fri', 'Thu']
Frozenset: frozenset({'Thu', 'Mon', 'Fri', 'Tue'})
Lỗi: 'frozenset' object does not support item assignment

Đặc điểm quan trọng

  • Immutable: Không thể add/remove/update
  • Hashable: Có thể dùng làm key dict, hoặc phần tử của set khác
  • Hỗ trợ phép toán set: union, intersection, difference, symmetric_difference

Ví dụ: Dùng frozenset làm key dict

# set thông thường KHÔNG thể làm key dict (unhashable)
# d = {set([1,2]): "value"}  # TypeError

# frozenset CÓ thể làm key
permissions = {
    frozenset(['read', 'write']): "Editor",
    frozenset(['read']): "Viewer",
    frozenset(['read', 'write', 'execute']): "Admin"
}

user_perms = frozenset(['read', 'write'])
print(permissions[user_perms])  # Editor

Khi nào dùng frozenset?

  • Cần set làm key trong dict
  • Cần set làm element trong set khác
  • Cần đảm bảo dữ liệu không bị thay đổi sau khi tạo (constant)
  • Cache/memoization với key là tập hợp