python创建一个空集合,如何在Python中创建一组集合?

在Python中尝试创建一个集合的集合时遇到了问题,由于内部集合是可变的,导致无法直接添加到集合中。解决方案是使用不可变的`frozenset`来替代,这样可以确保集合内的元素是唯一的,而不会出现类型错误。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

I'm trying to make a set of sets in Python. I can't figure out how to do it.

Starting with the empty set xx:

xx = set([])

# Now we have some other set, for example

elements = set([2,3,4])

xx.add(elements)

but I get

TypeError: unhashable type: 'list'

or

TypeError: unhashable type: 'set'

Is it possible to have a set of sets in Python?

I am dealing with a large collection of sets and I want to be able to not have to deal duplicate sets (a set B of sets A1, A2, ...., An would "cancel" two sets if Ai = Aj)

解决方案

Python's complaining because the inner set objects are mutable and thus not hashable. The solution is to use frozenset for the inner sets, to indicate that you have no intention of modifying them.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值