共享常见项目的Python聚合列表

发布于 2025-02-06 15:49:46 字数 280 浏览 2 评论 0原文

我正在寻找一个函数来汇总具有共同项目的列表。我想到的具体示例是以下情况:

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

如您所见,共享共同项目的所有列表都被捆绑在一起。列表的顺序或输出列表中的项目无关紧要。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

眉黛浅 2025-02-13 15:49:46

也许蛮力解决方案为您提供帮助:

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)

输出:

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

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']]
风吹雪碎 2025-02-13 15:49:46

您可以使用 connected_components 来自 networkx package package package:

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

You could use connected_components from the networkx package:

>>> 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']]
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文