【问题标题】:Graph Relationship between list of tuples [duplicate]图元组列表之间的关系[重复]
【发布时间】:2019-09-26 14:34:30
【问题描述】:

我有一个元组列表,比如说

tuplist = [('a','b'),('a','c'),('e','f'),('f','c'),('d','z'),('z','x')]

我正在尝试获取以下内容:

('a','b','c','e','f'),('d','z','x')

这是链接在一起的所有元素(就像图论中的树) 上述元组中的顺序(也可以是列表)无关紧要。

我已经设法获得单个元素的所有链接的字典,但我正在努力以一种干净有效的方式获得最终结果...... 到目前为止,这是我的代码:

ll=[('a','b'),('a','c'),('e','f'),('f','c'),('d','z'),('z','x')]
total = {}
total2={}
final=[]
for element in set([item for sublist in ll for item in sublist]):
    tp = []
    for tupl in ll:
        if element in tupl: 
            tp.append(tupl)

    tp = list(frozenset([item for sublist in tp for item in sublist]))
    total[element] = tp
print(total)

【问题讨论】:

标签: python list tuples


【解决方案1】:

this post 类似,您要查找的内容称为图的连通分量。一个简单的方法是用networkx建一个图,找到connected_components

tuplist = [('a','b'),('a','c'),('e','f'),('f','c'),('d','z'),('z','x')]

import networkx as nx 

G=nx.Graph()
G.add_edges_from(tuplist)
list(nx.connected_components(G))
# [{'a', 'b', 'c', 'e', 'f'}, {'d', 'x', 'z'}]

【讨论】:

  • 我在搜索过程中没有看到任何提及这一点,但我对图论并不熟悉,只是在寻找解决我的问题时偶然发现了它。非常感谢!
【解决方案2】:

可选的递归解决方案,虽然不如@yatu 的解决方案networkx 优雅:

tuplist = [('a','b'),('a','c'),('e','f'),('f','c'),('d','z'),('z','x')]
def get_graphs(start, c = [], seen = []):
  _r = [b for a, b in tuplist if a == start and b not in seen]+[a for a, b in tuplist if b == start and a not in seen]
  if _r:
     yield from [i for b in _r for i in get_graphs(b, c=c+[start, b, *_r], seen = seen+[start, b])]
  else:
     yield set(c)
     _r = [a for a, _ in tuplist if a not in seen]
     yield from ([] if not _r else get_graphs(_r[0], c = [], seen= seen))


result = list(get_graphs(tuplist[0][0]))
final_result = [a for i, a in enumerate(result) if all(all(k not in b for k in a) for b in result[i+1:])]
to_tuples = list(map(tuple, final_result))

输出:

[('f', 'e', 'a', 'c', 'b'), ('z', 'd', 'x')]

【讨论】:

    猜你喜欢
    • 2022-12-20
    • 2017-02-17
    • 2017-11-01
    • 1970-01-01
    • 2019-10-22
    • 2021-08-18
    • 1970-01-01
    • 2023-03-17
    • 2012-03-10
    相关资源
    最近更新 更多