Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing sublists from a list of lists

Tags:

python

list

set

I'm trying to find the fastest way to solve this problem, say I have a list of lists:

myList = [[1,2,3,4,5],[2,3],[4,5,6,7],[1,2,3],[3,7]]

I'd like to be able to remove all the lists that are sublists of one of the other lists, for example I'd like the following output:

myList = [[1,2,3,4,5],[4,5,6,7],[3,7]]

Where the lists [2,3] and [1,2,3] were removed because they are completely contained in one of the other lists, while [3,7] was not removed because no single list contained all those elements.

I'm not restricted to any one data structure, if a list of lists or a set is easier to work with, that would be fine too.

The best I could come up with was something like this but it doesn't really work because I'm trying to remove from a list while iterating over it. I tried to copy it into a new list but somehow I couldn't get it working right.

for outter in range(0,len(myList)):
outterSet = set(myList[outter])
for inner in range(outter,len(myList)):
    innerSet = set(myList[inner])
    if innerSet.issubset(outterSet):
        myList.remove(innerSet)

Thanks.

like image 551
doddy Avatar asked Nov 09 '17 19:11

doddy


People also ask

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

Our first approach is to use set comprehension with sorted tuple. In every iteration in the list, we convert the current sublist to a sorted tuple, and return a set of all these tuples, which in turn eliminates all repeated occurrences of the sublists and thus, remove all repeated rearranged sublists.

How do you get rid of an index in a list?

You can use the pop() method to remove specific elements of a list. pop() method takes the index value as a parameter and removes the element at the specified index. Therefore, a[2] contains 3 and pop() removes and returns the same as output. You can also use negative index values.


1 Answers

The key to solving your problem is a list of sets:

lists = [[1,2,3,4,5],[2,3],[4,5,6,7],[1,2,3],[3,7]]

sets = [set(l) for l in lists]

new_list = [l for l,s in zip(lists, sets) if not any(s < other for other in sets)]

This converts the inner lists to sets, compares each set to every other set to see if it is contained within it (using the < operator) and, if it is not strictly contained within another set, adds the original list to the new list of lists.

like image 183
yinnonsanders Avatar answered Nov 03 '22 18:11

yinnonsanders