Reputation: 682
I would like to select only those sets from a list of sets that are subsets of another set, so essentially that:
sets = [{1, 2, 3}, {6, 7, 8}]
s = {1, 2, 3, 4, 5, 6, 7}
list(compress(sets, [sub <= s for sub in sets]))
This works but it feels wrong to first evaluate the list comprehension and afterwards using compress. Is there a way to index sets directly, like:
sets[[sub <= s for sub in sets]] ### This does not work!
Upvotes: 2
Views: 39
Reputation: 11073
Try this:
[i for i in sets if all(j in s for j in i)]
Test:
In [226]: sets = [{1, 2, 3}, {6, 7, 8}, {1,2}, {3}, {7,1}, {7,8}, {8}]
In [227]: s = {1, 2, 3, 4, 5, 6, 7}
In [228]: [i for i in sets if all(j in s for j in i)]
Out[228]: [{1, 2, 3}, {1, 2}, {3}, {1, 7}]
Upvotes: 2