0

I have a list of lists and am wanting to merge together all lists if any element of a list is in both lists.

For example, consider this list of lists: [[0],[1,2,3,4],[4,5,6],[6,7,8]]

The output should be: [0],[1,2,3,4,5,6,7,8]

1 Answers1

0

Try the following. Tested in python3.

def mergeOrNot(list1,list2):
    merge=False
    for item in list1:
        if item in list2:
            merge=True
            break
    return merge

def uniqueList(list1,list2):
    result = set()
    for item in list1:
        result.add(item)
    for item in list2:
        result.add(item)
    return result

def cleverMergeLists(lists):
    anotherLoopRequired=False
    newList = []
    for myList in lists:
        addMyList=True
        if not anotherLoopRequired:
            for myList2 in lists:
                if not anotherLoopRequired:
                    if(myList==myList2):
                        continue
                    if(mergeOrNot(myList,myList2)):
                        anotherLoopRequired=True
                        addMyList=False
                        newList.append(uniqueList(myList,myList2))
                else:
                    newList.append(myList2)
            if(addMyList):
                newList.append(myList)
    if anotherLoopRequired:
        return cleverMergeLists(newList)
    else:
        return newList


print(cleverMergeLists([[0],[1,2,3,4],[4,5,6],[6,7,8]]))

Outputs the following:

[0], {1, 2, 3, 4, 5, 6, 7, 8}] 

Can't vouch for efficiency or anything, and I've only tested it on your list, so may contain bugs or not work for some cases.

The cleverMergeLists function loops over items in the list, and works out if two items need merging. If they do, it calls itself on a new list with two of the items merged, if not, it returns the list as was passed to it.