简体   繁体   中英

Is there a Python datatype for unordered sets of sets?

I want to store sets A and B , in a set C . My condition is that if set A = {a,b} and set B = {b,a}

Then set A is equal to set B

Set C will then be = {{a,b}}

Is there a datatype which supports something like this?

The frozenset() type meets your criteria:

>>> A = frozenset({"a", "b"})
>>> B = frozenset({"b", "a"})
>>> A == B
True
>>> frozenset({ A, B })
frozenset({frozenset({'b', 'a'})})

Yes, and that datatype is just set . The trick is that the inside sets have to be frozenset s, the immutable counterpart of set , for them to be placed inside another set. You may also want to make the outer set a frozenset , depending on what you want to do with it; for example, if you want to stick these sets inside more layers of sets indefinitely, it's probably easier to go with frozensets for everything.

>>> A = frozenset(['a', 'b'])
>>> B = frozenset(['b', 'a'])
>>> C = {A, B}
>>> C
set([frozenset(['a', 'b'])])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM