Merge lists containing similar members

I’ve got a list like – {{0},{1},{2,4},{3,5},{3,4,2},{6}} – and I want – {{0},{1},{2,3,4,5},{6}] – where, in this example, the 2nd, 3rd, and 4th index are merged into a single list because they all have elements in common.

So far I have a solution but it requires some form of regression that I’ve yet to figure out.

I start with a ListGetItemAtIndex and Flatten the results to the same level as the first list. Then list the unique items. From there I compare the unique items of the unique items with the unique items (confused yet?). I couldn’t find a method for this so I resorted to a hack that I’m sure will break eventually. I convert the numbers to strings, concatenate them and then find the indices of the smaller list in the larger. If any of that list are empty lists, then I feed the sorted list back into the another set of identical nodes (hence the regression) until the last List.AllIndicesOf node has no empty lists.

There’s got to be an easier, more elegant way. Right? If not, how would I loop the set of nodes until I get a true value on the last node and report the final result?

@Greg_McDowell Could you please post your file?

Sure… but not that one… there’s way more going on that doesn’t matter to this part of it. One clarification, the list I started with in the example should be more like – {{0},{1},{2,4},{3,5},{3,4,2},{5,2},{6}} – and with the same desired output – {{0},{1},{2,3,4,5},{6}}. In the attached DYN, with this list, I had to run it through the set of nodes twice to get it where it needs to be.

Merge List Example.dyn (28.0 KB)

@Greg_McDowell There are a few solutions here:

The one below is just one of them.

_list = IN[0]
l=_list[:]
	
len_l = len(l)
i = 0
while i < (len_l - 1):
    for j in range(i + 1, len_l):
        i_set = set(l[i])
        j_set = set(l[j])
        if len(i_set.intersection(j_set)) > 0:
            l.pop(j)
            l.pop(i)
            ij_union = list(i_set.union(j_set))
            l.append(ij_union)
            len_l -= 1
            i -= 1
            break

    i += 1
    
OUT=sorted(l)

Man. I tried Googling this for hours and never found anything. Then you shared the solution and I thought, “how did I miss that?” I plugged in the title of the post into Google and poof! It was the number 2 answer (this post was number 1)! Crazy. Thanks!

One thing I left out is a need to know which indices where combined. In the example it would be a list like {{0},{1},{2,3,4,5,},{6}}. Any ideas?

Sorry, bad example - it’s the same list! I think I found a solution.

This list – {{0},{2,4},{1},{3,5},{3,4,2},{6},{5,2}} – returns this merged list (sorting doesn’t really matter here) – {{0},{1},{6},{2,3,4,5}} – and this list of indices of the original list that matches – {{0},{2},{5},{1,3,4,6}}