Skip to content Skip to sidebar Skip to footer

Comparing Contents Of 2 Lists Of Lists

Here's the task I am having trouble with: Given 2 lists of lists, filter them down to only items that have nothing in common. E. g. if inner lists are identical, filter them out. I

Solution 1:

I'm not sure that I understand you, but I'm gonna give it a shot.

# first, get all elements from each list as a flat set.
import itertools
set1 = set(itertools.chain.from_iterable(list1))
set2 = set(itertools.chain.from_iterable(list2))

#Now, figure out which elements they have in common
common_elements = set1 & set2

#Now eliminate inner lists which have elements in the common set
new_list1 = [lst for lst in list1 if not any(x in common_elements for x in lst)]
new_list2 = [lst for lst in list2 if not any(x in common_elements for x in lst)]

Note that I can do this because the sublists hold hashable objects.

Solution 2:

I think a filter like this is what you want

filter(lambda sublist:notany(set(sublist).intersection(x) for x in list2),list1)

Post a Comment for "Comparing Contents Of 2 Lists Of Lists"