Python: Iterate Through List of Sublists, Merging Sublists with Shared Elements

Viewed 35

Related posts on here seem to be different enough that I'm not sure how to apply it to my use case.

I have a list containing sublists; each sublist consists of a pair of elements:

sample = [['tree', 'forest'], ['dog', 'cat'], ['man', 'boy'], ['man', 'woman'], ['boy', 'woman']] 

In some cases, pairs share common elements (both 'man' and 'woman' occur in two different pairs).

I want to run this list of lists through a function which will merge all overlapping pairs into one:

output = [['tree','forest'],['dog','cat'],['man','boy','woman']]

So far I've tried turning the sublists into sets and adding them together if they overlap, but I never get the desired output, so I think my programming intuition is too weak here.

This is a shortened version of the data I'm using, but ideally I want to handle an indefinite number of pairs with an indefinite number of overlaps.

0 Answers
Related