简体   繁体   English

共享一个共同项目的 Python 聚合列表

[英]Python aggregate lists that share a common item

I'm looking for a function to aggregate lists that have a common item.我正在寻找一个函数来聚合具有共同项目的列表。 The specific example I had in mind was the following case:我想到的具体例子是以下案例:

inputs = [['a','b'], ['a','c'], ['b','d'], ['e','f'], ['g','h'], ['i','k'], ['k','l']]
aggregated_output = [['a','b','c','d'],['e','f'],['g','h'],['i','k','l']]

as you can see, all the lists that share a common item have been bunched together.如您所见,共享一个共同项目的所有列表都被捆绑在一起。 The order of the lists or the items in the lists in the output does not matter.输出中列表或列表中的项目的顺序无关紧要。

Maybe Brute-Force Solutions help you:也许蛮力解决方案可以帮助您:

inputs = [['a','b'], ['a','c'], ['b','d'], ['e','f'], ['g','h'], ['i','k'], ['k','l']]

res = []
for arr in inputs:
    flaq = False
    for r in res:
        for a in arr:
            if a in r:
                r += [a for a in arr if not a in r]
                flaq = True
                break
    if not flaq:
        res.append(arr)
print(res)

Output:输出:

[['a', 'b', 'c', 'd'], ['e', 'f'], ['g', 'h'], ['i', 'k', 'l']]

You could use connected_components from the networkx package:您可以使用networkx包中的connected_components

>>> import networkx as nx
>>> edges = [['a', 'b'], ['a', 'c'], ['b', 'd'], ['e', 'f'], ['g', 'h'], ['i', 'k'], ['k', 'l']]
>>> graph = nx.Graph()
>>> graph.add_edges_from(edges)
>>> [list(c) for c in nx.connected_components(graph)]
[['a', 'c', 'd', 'b'], ['f', 'e'], ['h', 'g'], ['k', 'i', 'l']]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM