i’m trying to figure out how i can identify which objects are a subset/superset within the list that holds them. and thereby remove them from the list.
if i have list a = [ {'john-123'}, {'john-123','john-234'}, {'john-123','john-234','johnnybegood'} ]
the first two are subsets of the last one.
i’ve found a lot about comparing two different sets, but not sure how to implement that into an iteration
i’ve tried something like this:
for j in a: frequency = sum(j.issubset(b) for b in a) print(frequency)
but no dice
Advertisement
Answer
The problem in your approach is that you test every element in the list against every element in the list, not every other element. Since every set is a subset of itself, you will always get the whole list as an answer.
Try this:
a = [{1}, {2}, {1,2}, {1,3}, {1,3,4}]
Clearly, {1,2}
and {1,3,4}
are not subsets of other sets in a
.
subsets = [b for b in a if any(b.issubset(c) and b != c for c in a)] print(subsets) [{1}, {2}, {1, 3}]