You need to enable JavaScript to run this app. Python中打印嵌套集合时如何不显示frozenset关键字
优惠活动
大模型
产品
解决方案
定价
更多

Python中打印嵌套集合时如何不显示frozenset关键字

frozenset的默认字符串表示自带类名标识,原生无法直接输出{{1,2}}格式,可通过以下两种方案实现需求:

方案1:仅打印时临时格式化

无需修改原有业务逻辑,只在输出时做字符串拼接即可:

t = [[], [1, 2], [5], [1, 2, 5], [1, 2, 3, 4], [1, 2, 3, 6]]
t1 = set(frozenset(i) for i in t)

# 逐个格式化frozenset元素
format_items = []
for item in t1:
    if not item:
        format_items.append("{}")
    else:
        format_items.append(str(set(item)))

print("{" + ", ".join(format_items) + "}")

运行后输出效果:

{{1, 2}, {1, 2, 5}, {1, 2, 3, 4}, {}, {1, 2, 3, 6}, {5}}

方案2:自定义frozenset子类

如果需要高频使用该格式输出,可继承frozenset重写__repr__方法,保留frozenset全部原生特性(可哈希、不可修改)的同时适配输出格式:

class FormatFrozenSet(frozenset):
    def __repr__(self):
        if not self:
            return "{}"
        return str(set(self))

t = [[], [1, 2], [5], [1, 2, 5], [1, 2, 3, 4], [1, 2, 3, 6]]
t1 = set(FormatFrozenSet(i) for i in t)
print(t1)

运行输出和方案1完全一致。


内容的提问来源于stack exchange,提问作者Phong Diep

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.10 14:54:00