Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can you remove superset lists from a list of lists in Python?

I have a list of lists in Python like the following:

[[1,2,3],[2,3],[2,4,3],[4,5],[5]]

I want to remove all the inner lists that are a superset (a list that contain all the elements of another list, but with additional elements) of another inner list. For the example above, removing the supersets should result in the following:

[[2,3],[5]]

How can I accomplish this?

like image 758
apriori Avatar asked Jun 01 '18 01:06

apriori


People also ask

How do I remove a list from a list in Python?

The remove() method removes the first matching element (which is passed as an argument) from the list. The pop() method removes an element at a given index, and will also return the removed item. You can also use the del keyword in Python to remove an element or slice from a list.

How do I remove all matching values from a list in Python?

Python3. Method 3 : Using remove() In this method, we iterate through each item in the list, and when we find a match for the item to be removed, we will call remove() function on the list.

How do you remove an object from a list in Python?

To remove items (elements) from a list in Python, use the list functions clear(), pop(), and remove(). You can also delete items with the del statement by specifying a position or range with an index or slice.


2 Answers

A set can only be a subset of another if it is smaller, thus by iterating over the sets in ascending order of size, we can check each element against the previously found minimal subsets to know if it is a minimal subset.

def get_minimal_subsets(sets):
    sets = sorted(map(set, sets), key=len)
    minimal_subsets = []
    for s in sets:
        if not any(minimal_subset.issubset(s) for minimal_subset in minimal_subsets):
            minimal_subsets.append(s)

    return minimal_subsets

l = [[1,2,3],[2,3],[2,4,3],[4,5],[5]]

print(get_minimal_subsets(l))  # [{5}, {2, 3}]
like image 141
Olivier Melançon Avatar answered Sep 23 '22 15:09

Olivier Melançon


You can use a list comprehension:

d = [[1,2,3],[2,3],[2,4,3],[4,5],[5]]
new_d = [i for i in d if not any(all(c in i for c in b) and len(b) < len(i) for b in d)]

Output:

[[2, 3], [5]]
like image 29
Ajax1234 Avatar answered Sep 22 '22 15:09

Ajax1234