In Python, how to write a collection containing a collection?

We know that in Python a set can be defined by writing out all its elements as follows:

a_set={1,"xyz"} 

And Python books all say that collection elements can be any data types. Therefore, we should be able to record a set containing a set. I tried to write it as:

 a_set={1,{"xyz"}} 

But IDLE reported an error:

 Traceback (most recent call last): File "<pyshell#58>", line 1, in <module> a_set={1,{"xyz"}} TypeError: unhashable type: 'set' 

I think this may be because Python is trying to understand this as a dictionary. Then, how to write a collection containing a collection in Python?

+7
source share
3 answers

The internal majority of the sets must be of type frozenset , which is an unchanged version of the set.

 >>> a_set = {1, frozenset(['xyz'])} >>> a_set set([1, frozenset(['xyz'])]) 

From docs :

class frozenset ([iterable])

Returns a new set or frozenset object whose elements are taken from an iterable. Set elements must be hashed. To represent sets of sets, internal sets must be frozenset objects. If iterable is not specified, a new empty set is returned.

+15
source

Sets can only store immutable objects, while sets themselves change. Therefore, a set cannot contain another set.

Use frozenset :

To represent sets of sets, internal sets must be frozenset objects.

+6
source

This example shows the use of frozenset :

 a_set = frozenset([1,2,3]) b_set = frozenset([1,3]) a_set_copy = frozenset([2,3,1]) set_of_sets = set([a_set, b_set, a_set_copy]) print set_of_sets # set([frozenset([1, 3]), frozenset([1, 2, 3])]) 
+1
source

All Articles