我正在尝试在Python中设置一组。我不知道该怎么做。从空集开始xx:xx = set([])# Now we have some other set, for exampleelements = set([2,3,4])xx.add(elements)但我明白了TypeError: unhashable type: 'list'要么TypeError: unhashable type: 'set'Python中是否可以有一组集合?我正在处理大量集合,所以我希望不必处理重复的集合(集合A1,A2,....的集合B,如果Ai = Aj,则“将取消”两个集合)
3 回答

眼眸繁星
TA贡献1873条经验 获得超9个赞
人们已经提到您可以使用Frozenset()做到这一点,所以我将添加一个代码来实现此目的:
例如,您要从以下列表列表中创建一组集合:
t = [[], [1, 2], [5], [1, 2, 5], [1, 2, 3, 4], [1, 2, 3, 6]]
您可以通过以下方式创建集合:
t1 = set(frozenset(i) for i in t)

慕神8447489
TA贡献1780条经验 获得超1个赞
所以我有完全相同的问题。我想制作一个可以作为一组集合使用的数据结构。问题在于集合必须包含不可变的对象。因此,您可以做的只是将其作为一组元组。对我来说很好!
A = set()
A.add( (2,3,4) )##adds the element
A.add( (2,3,4) )##does not add the same element
A.add( (2,3,5) )##adds the element, because it is different!
添加回答
举报
0/150
提交
取消