Python 正在合并设置为列表的对

Python 正在合并设置为列表的对,python,algorithm,list,set,Python,Algorithm,List,Set,我有输入集或列表,例如 输入: [[0,1],[0,2],[1,3],[4,5],[6]] or [[0,1],[0,2],[1,2],[1,3],[4,5],[6]] 我希望输出为 [[0,1,2,3],[4,5],[6]] 基本上,它将创建带有共享对的列表。数据类型可能有所不同。我在写python。欢迎使用伪代码或python代码。谢谢经过实验,我找到了答案: def pairs_to_whole(touching_pairs:list): out = [] while

我有输入集或列表,例如

输入:

[[0,1],[0,2],[1,3],[4,5],[6]] or [[0,1],[0,2],[1,2],[1,3],[4,5],[6]]
我希望输出为

[[0,1,2,3],[4,5],[6]]

基本上,它将创建带有共享对的列表。数据类型可能有所不同。我在写python。欢迎使用伪代码或python代码。谢谢

经过实验,我找到了答案:

def pairs_to_whole(touching_pairs:list):
    out = []
    while len(touching_pairs)>0:
        first, *rest = touching_pairs
        first = set(first)

        lf = -1
        while len(first)>lf:
            lf = len(first)

            rest2 = []
            for r in rest:
                if len(first.intersection(set(r)))>0:
                    first |= set(r)
                else:
                    rest2.append(r)     
            rest = rest2

        out.append(first)
        touching_pairs = rest
    return out

一种可能性是使用递归:

def get_groups(d, l, s=[]):
   if not (r:=[i for i in d if any(j in l for j in i) and i not in s]):
      yield list(set(l))
      if (new_r:=[i for i in d if i not in s]):
         yield from get_groups(d, new_r[0], s=s+[new_r[0]])
   else:
      yield from get_groups(d, l+[i for k in r for i in k], s=s+r)

vals = [[0,1],[0,2],[1,2],[1,3],[4,5],[6]]
print(list(get_groups(vals, vals[0])))
输出:

[[0, 1, 2, 3], [4, 5], [6]]

您可以使用集合字典来表示使用最小值作为键的组。这将允许您通过直接访问由其成员组成的组来逐步合并组。逐步删除合并的子组(直到不再删除)将为您留下所需的分组

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]]

你试过什么?它到底有什么问题?它也是一个集合还是一个列表(你展示的是后者)——这是一个很大的区别。如果集合或元组更容易使用,我可以使用并更改数据类型。@Zek'iB.Ulu,
[[6,0,1],[0,2],[1,3],[4,5],[6]
?请看这个问题:谢谢你的评论!但是代码给出了RecursionError:在中超过了最大递归深度comparison@Zek“iB.Ulu您能发布您试用过的输入示例吗?我刚刚运行了您的全部代码。输入样本必须是VAL isuppose@Zek“iB.Ulu奇怪,它在两个样本以及RomanPerekhrest建议的
[[6,0,1]、[0,2]、[1,3]、[4,5]、[6]]
上都运行良好。您使用的是什么版本的Python?