I have a number of sets with each set representing the unique items in a single data file. Some of these sets are subsets of others, some are identical.
Is there a primitive or a module that lets me sort the sets such that I get something like
A <= B <= C <= D <= E
et cetera for the sets A, B, C, D, E, F?
I.e. sort not the items from a set, but instead sort the sets themselves by their relation as subsets and supersets of each other?
Just put them in a list and sort them. If a set is a subset of another set their <=
relationship is True, and this extends to sorting. In other words, what you want is the default sort order already.
Demo:
>>> A = {1, 2}
>>> B = A | {3}
>>> C = B.copy()
>>> D = C | {4}
>>> A <= D
True
>>> [B, C, D, A]
[set([1, 2, 3]), set([1, 2, 3]), set([1, 2, 3, 4]), set([1, 2])]
>>> sorted([B, C, D, A])
[set([1, 2]), set([1, 2, 3]), set([1, 2, 3]), set([1, 2, 3, 4])]
To be explicit: two sets that are not a subset of the other return False for all ordering operations, and their relative order when sorted won't change. This means that disjoint sets in the sequence will throw a spanner in the works, as they violate the expectation of total ordering sorting has.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With