基于具有公共元素来组合列表列表中的元素

时间:2019-04-29 03:37:14

标签: python list

我有一个这样的列表清单

list=[[a], [b], [c], [d],[e],[f], [a,f], [b,c], [c,e], [b, d,f]]

请注意,它包括单打和组合。

我想做的是对列表进行迭代,以便当且仅当它们共享至少一个公共条目时,才将这些子组件的每种可能组合的新列表追加到列表中。

所以产品如下

list2=[[a], [b], [c], [d],[e],[f], [a,f], [b,c], [c,e], [b, d,f], **[b,c,e], [a,b,d,f], [b,c,d,f], [b,c,d,e,f], [a,b,c,d,e,f]]**

请注意,列表的新部分包含列表的原始列表

1 个答案:

答案 0 :(得分:1)

def similar(x):
    prev_l = 0
    while prev_l != len(x):
        to_add = []
        prev_l = len(x)
        for i in x:
            if len(i) == 1:
                continue
            for j in x:
                if len(j) == 1:
                    continue
                if any([_ in j for _ in i]) and not any([set(i+j) == set(_) for _ in x]) and not any([set(i+j) == set(_) for _ in to_add]) and i != j:
                    to_add.append(list(set(i+j)))
        x += to_add
    return x

输入:

>>> l = [['a'], ['b'], ['c'], ['d'],['e'],['f'], ['a','f'], ['b','c'], ['c','e'], ['b', 'd','f']]
>>> similar(l)

输出:

>>> l
[['a'], ['b'], ['c'], ['d'], ['e'], ['f'], ['a', 'f'], ['b', 'c'], ['c', 'e'], ['b', 'd', 'f'], ['b', 'a', 'd', 'f'], ['b', 'e', 'c'], ['b', 'd', 'c', 'f'], ['b', 'a', 'f', 'd', 'c'], ['b', 'f', 'e', 'd', 'c'], ['b', 'a', 'f', 'e', 'd', 'c']]

我应该注意,在最坏的情况下,它有O(n^3)。如果您将其用于一些杂乱无章的战争中,那么我就不会太担心,因为无论如何它都有O(n^3),但是如果不是这样,则绝对应该填充一个距离矩阵,然后在其中寻找邻接关系。

相关问题