Sohn
Sohn

Reputation: 166

Common elements of list of lists of lists

I have a list of lists of lists. Is there any way that I can get the intersection of these. For eg.:

a=[[[1, 2], [2, 3]], [[1, 2], [3, 4]], [[1, 2], [1, 4], [2, 4]]]

From this how can I get [1,2] as the result, which is the common element of those 3 lists of lists ?

Upvotes: 1

Views: 978

Answers (1)

mgilson
mgilson

Reputation: 309929

I might do it something like this:

>>> sets = [set(tuple(lst) for lst in sublist) for sublist in a]
>>> sets
[set([(1, 2), (2, 3)]), set([(1, 2), (3, 4)]), set([(1, 2), (2, 4), (1, 4)])]
>>> sets[0].intersection(*sets[1:])
set([(1, 2)])

The first step is to realize that some python data-structures can help. set can find the intersection easily if the items are hashable. list aren't hashable, but tuple are and converting between the two is easy. So the first step is to turn your sublists of lists into a sets of tuple.

That's accomplished by the first line:

sets = [set(tuple(lst) for lst in sublist) for sublist in a]

From here, assuming that you have at least one set in sets, you can just pick off the first one and intersect it with all the rest1. Writing it out slightly more verbosely than above:

first_set = sets[0]
rest_of_sets = sets[1:]
intersection = first_set.intersection(*rest_of_sets)

Now you have an intersection (it's a set that contains tuple). We can easily unravel that back into lists if you want:

list_intersection = [list(item) for item in intersection]

1You can also write it as: intersection = set.intersection(*sets) -- It might even be a tiny bit more efficient...

Upvotes: 2

Related Questions