[Solved] python about linking sublist with same number together


To group the sublists in a general way you can:

Code:

def linking_sublists(lists):
    index = {}
    sets = []
    for l in lists:
        found = None
        for i in l:
            if i in index:
                # this list has an element we have already seen
                if found:
                    # combine two sets
                    to_remove = index[i]
                    if found != to_remove:
                        for j in index[i]:
                            found.add(j)
                            index[j] = found
                        to_remove.clear()
                else:
                    found = index[i]

        if found is not None:
            s = found
            for i in l:
                s.add(i)
        else:
            s = set(l)
            sets.append(s)
        for i in l:
            index[i] = s

    return [list(sorted(s)) for s in sets if s]

How:

This function uses sets and an index dict to group any list with matching elements into sets and track which elements are already in a set.

Test Code:

list_2 = [[2, 3], [4, 3], [6, 5], [7, 6], [7, 8], [13, 14], [30, 32]]
print(linking_sublists(list_2))

list_3 = [[2, 3], [4, 3], [6, 5], [7, 6], [7, 8], [30, 32], [4, 5], [3, 4]]
print(linking_sublists(list_3))

Results:

[[2, 3, 4], [5, 6, 7, 8], [13, 14], [30, 32]]
[[2, 3, 4, 5, 6, 7, 8], [30, 32]]

1

solved python about linking sublist with same number together