Is there a way to remove lists from a list that contain the sublists?
Let's say that I have 5 elements from a to e.
I found all combinations from size 0 to size 5 below:
all_combinations = [[], ['a'], ['b'], ['c'], ['d'], ['e'], ['a', 'b'], ['a', 'c'], ['a', 'd'], ['a',
'e'], ['b', 'c'], ['b', 'd'], ['b', 'e'], ['c', 'd'], ['c', 'e'], ['d', 'e'],
['a', 'b', 'c'], ['a', 'b', 'd'], ['a', 'b', 'e'], ['a', 'c', 'd'], ['a', 'c',
'e'], ['a', 'd', 'e'], ['b', 'c', 'd'], ['b', 'c', 'e'], ['b', 'd', 'e'],
['c', 'd', 'e'], ['a', 'b', 'c', 'd'], ['a', 'b', 'c', 'e'], ['a', 'b',
'd', 'e'], ['a', 'c', 'd', 'e'], ['b', 'c', 'd', 'e'], ['a', 'b', 'c', 'd', 'e']]
Now let's say I want to remove some of these combinations that contain the sublists:
sublists = [['a', 'c'], ['c', 'd'], ['b', 'e']]
Is there a simple way of doing this? I should only be left with combinations that don't contain these sublists. I should only end up with lists where a and c are not together, c and d are not together, and b and e are not together.
EDIT: want to get output like this:
valid_combinations = [[], ['a'], ['b'], ['c'], ['d'], ['e'], ['a', 'b'],
['a', 'd'], ['a', 'e'], ['b', 'c'], ['b', 'd'],
['c', 'e'], ['d', 'e'], ['a', 'b', 'd'],
['a', 'd', 'e']]
You can use sets to see if the complete list of items in sublists
is contained within the sublist of all_combinations
:
>>> [sl for sl in all_combinations if not any(set(e)<=set(sl) for e in sublists)]
[[], ['a'], ['b'], ['c'], ['d'], ['e'], ['a', 'b'], ['a', 'd'], ['a', 'e'], ['b', 'c'], ['b', 'd'], ['c', 'e'], ['d', 'e'], ['a', 'b', 'd'], ['a', 'd', 'e']]
>>> _==valid_combinations
True