当前位置:首页>python>Python 列表转不可变集合(frozenset)完整案例

Python 列表转不可变集合(frozenset)完整案例

  • 2026-10-11 06:25:15
Python 列表转不可变集合(frozenset)完整案例

基础知识点

  1. 普通集合 set():可变,支持增删元素,不能作为字典key、放入集合
  2. 冻结集合 frozenset():不可变(只读),元素无法修改、添加、删除,属于哈希类型,可当字典键/存入集合
  3. 转换逻辑:列表 → frozenset,自动去重,无序

案例1:基础转换、去重特性

# 原始列表(包含重复元素)
num_list = [1, 2, 2, 3, 4, 4, 5]

# 转为不可变冻结集合
immutable_set = frozenset(num_list)

print("原列表:", num_list)
print("不可变集合:", immutable_set)
print("类型:", type(immutable_set))

# 尝试修改会直接报错
try:
    immutable_set.add(6)
except AttributeError as e:
    print("修改报错:", e)

输出:

原列表: [1, 2, 2, 3, 4, 4, 5]
不可变集合: frozenset({1, 2, 3, 4, 5})
类型: <class 'frozenset'>
修改报错: 'frozenset' object has no attribute 'add'

案例2:字符串列表转frozenset

str_list = ["apple", "banana", "apple", "orange"]
fs = frozenset(str_list)

print(fs)
# 无法删除元素
try:
    fs.remove("apple")
except AttributeError as err:
    print("删除失败:", err)

输出:

frozenset({'orange', 'apple', 'banana'})
删除失败: 'frozenset' object has no attribute 'remove'

案例3:frozenset 独有优势(可做字典键)

普通set可变,不能当字典key;frozenset不可变、可哈希,能作为key:

data1 = [10, 20, 30]
data2 = [20, 30, 40]

# 转不可变集合
key1 = frozenset(data1)
key2 = frozenset(data2)

# 用frozenset做字典键
info_dict = {
    key1: "第一组数据",
    key2: "第二组数据"
}

print(info_dict)
print(info_dict[frozenset([10, 20, 30])])

# 对比:普通set会报错
try:
    bad_key = set([1, 2])
    test_dict = {bad_key: "测试"}
except TypeError as e:
    print("普通set不能做字典键:", e)

输出:

{frozenset({10, 20, 30}): '第一组数据', frozenset({20, 30, 40}): '第二组数据'}
第一组数据
普通set不能做字典键: unhashable type: 'set'

案例4:frozenset 存入普通set集合

同样依靠不可变、可哈希特性:

list_a = [1, 3, 5]
list_b = [2, 4, 6]

fs1 = frozenset(list_a)
fs2 = frozenset(list_b)

# 把两个不可变集合放进普通集合
container = {fs1, fs2}
print(container)

输出:

{frozenset({1, 3, 5}), frozenset({2, 4, 6})}

案例5:frozenset 转回列表

如果后续需要恢复列表结构:

old_list = [5, 3, 1, 3]
fs = frozenset(old_list)

# 转回列表
new_list = list(fs)
print("转回列表:", new_list)

核心总结

  1. 转换语法:frozenset(列表)
  2. 特性:自动去重、无序、完全不可修改
  3. 适用场景:
    • 需要集合去重,但不允许数据被篡改
    • 需要把集合作为字典key、存入另一个集合
  4. 区分对比 | 类型 | 可变 | 可哈希 | 增删方法 | |------|------|--------|----------| | set  | ✅ 可变 | ❌ 不可哈希 | add/remove/pop | | frozenset | ❌ 不可变 | ✅ 可哈希 | 无修改方法 |

最新文章

随机文章