Home > Back-end >  How I can subset a list of lists?
How I can subset a list of lists?

Time:11-22

I have the following two lists:

list_dummy = [['a', 'b', 'c'], ['d', 'b', 'c'], ['a', 'b', 'd'], ['d', 'a', 'c'] ]
must_have = ['a', 'b']

I want to "subset" the first list, meaning that I only want to keep the lists within list_dummy that have the elements a and b

The expected result should be:

list_sub = [['a', 'b', 'c'], ['a', 'b', 'd']]

How I can do this in python and please also consider that the list_dummy might be large so some scalable solution would be appreciated.

CodePudding user response:

You can convert them to sets and then check if their intersection is same as the must_have set.

list_dummy = [['a', 'b', 'c'], ['d', 'b', 'c'], ['a', 'b', 'd'], ['d', 'a', 'c'] ]
must_have = ['a', 'b']
must_have_set = set(must_have)
print([x for x in list_dummy if set(x) & must_have_set == must_have_set])

CodePudding user response:

You can use issubset

list_dummy = [['a', 'b', 'c'], ['d', 'b', 'c'], ['a', 'b', 'd'], ['d', 'a', 'c']]
must_have = ['a', 'b']
list_sub = [i for i in list_dummy if set(must_have).issubset(i)]
print(list_sub)
  • Related