您可以使用集合字典来表示使用最小值作为键的组。这将允许您通过直接访问由其成员组成的组来逐步合并组。逐步消除合并的子组(直到不再删除)将为您留下所需的分组。
from collections import deque
def groupPairs(pairs):
links = dict() # each value paired to a set of larger values
addLinks = deque() # values to be added to a group
for a,*b in map(sorted,pairs):
links[a] = set() # create empty group for each lowest value
addLinks.append((a,b)) # queue addition of paired values
while addLinks:
a,values = addLinks.popleft() # next addition of pairs
if not values or a not in links: continue
links[a].update(values) # add the paired values to the group
addLinks.append((a,[c for b in values for c in links.pop(b,[])])) # remove and queue more
return [ [k,*v] for k,v in links.items() ]
P = [[0,1],[0,2],[1,3],[4,5],[6]]
gp = groupPairs(P)
print(gp)
# [[0, 1, 2, 3], [4, 5], [6]]
P = [[0,1],[0,2],[1,2],[1,3],[4,5],[6]]
gp = groupPairs(P)
print(gp)
# [[0, 1, 2, 3], [4, 5], [6]]
P = [[6, 0, 1],[0,2],[1,3],[4,5],[6]]
gp = groupPairs(P)
print(gp)
# [[0, 1, 2, 3, 6], [4, 5]]