1

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']] 
1
  • [sl for sl in all_combinations if not any(set(e)>=set(sl) for e in sublists)] Commented Nov 2, 2020 at 17:10

3 Answers 3

3

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 
Sign up to request clarification or add additional context in comments.

Comments

0

Try this :

result = [item for item in all_combinations if item not in sublists] 

1 Comment

I believe OP wants to exclude any list that contains a sublist, this only excludes the ones that are equal to one of the sublists
0

One possible way is to use sets, in particular the function issuperset to check if a list contains all the elements of another. So, the following list comprehension returns all elements a of all_combinations that do not contain every element of any b in sublists

[a for a in all_combinations if all(not set(a).issuperset(set(b)) for b in sublists)] 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.