简体   繁体   English

在python中将有向图转换为无向图(列表数组)的快速方法?

[英]Fast way to convert directed to undirected graph (array of lists) in python?

I'm trying to convert a set of arcs to a set of edges for some simple visualization work. 我正在尝试将一组弧线转换为一组边线,以进行一些简单的可视化工作。

my arc data currently looks like: 我的弧数据当前看起来像:

(
  ['A','B',2],
  ['B','A',3],
  ['A','C',4],
  ['B','C',2],
)

I need to convert it to edges, so the directions are combined, looking like this: 我需要将其转换为边缘,因此将方向合并,如下所示:

(
  ['A','B',5],
  ['A','C',4],
  ['B','C',2],
)

I'm thinking there should be a very pythonic way to do this, but not sure what the most elegant way is. 我在想应该有一种非常pythonic的方法来做到这一点,但不确定最优雅的方法是什么。

Here's an approach using a dictionary where the keys are the ends of the arc in sorted order: 这是使用字典的一种方法,其中键是按排序顺序的弧的末端:

import collections
d = collections.defaultdict(int)
for n1, n2, v in arcdata:
    d[min(n1, n2), max(n1, n2)] += v
result = [[k[0], k[1], v] for k, v in d.iteritems()]

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

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