简体   繁体   English

Python:从带括号的边创建图节点

[英]python: creating graph nodes from a parenthesized edges

I'm trying to create a graph from an input which looks like this: 我正在尝试通过如下所示的输入创建图形:

(1 2) (2 3) (3 4) (4 1) 

the representation above is space-separated and each parenthesized argument represent a edge between two nodes. 上面的表示是用空格隔开的,每个带括号的参数表示两个节点之间的一条边。 I am not sure which kind of matrix representation will be easier to use.. a matrix-adjacency or linked list adjacency ? 我不确定哪种矩阵表示形式将更易于使用.. matrix-adjacencylinked list adjacency

Any ideas about how to parse such input? 关于如何解析此类输入的任何想法? and how to store it right away in the matrix for example? 以及如何立即将其存储在矩阵中?

Thanks in advance! 提前致谢!

In term of ease of use, matrix-adjacency is preferable, even the edge detection between two nodes happen in O(1) time. 在易用性方面,即使两个节点之间的边缘检测发生在O(1)时间,矩阵邻接也是可取的。 If your network is huge and sparse, you would want to avoid wasting too much space putting zeros in matrix-adjacency, then you should use linked list adjacency. 如果您的网络庞大且稀疏,则要避免浪费太多的空间,将零添加到矩阵邻接中,那么您应该使用链表邻接。 In your case, as it is a small graph, it doesn't matter much. 在您的情况下,由于它只是一个小图,所以没关系。

你可以这样解析

points = re.findall("\((\d+) (\d+)\)","(1 2) (2 3) (3 4) (4 1) ")

I would suggest building a dictionary which maps nodes to a set of nodes it is connected to. 我建议建一个字典,将节点映射到它所连接的一组节点。 This is assuming your edges are one-way. 这是假设您的边缘是单向的。

info = '(1 2) (2 3) (3 4) (4 1)'
info = info.replace('(','').replace(')','')
info = info.split(' ')
edges={};
for i in range(1,len(info)):
    if i%2 == 1:
        startnode = info[i-1]
        endnode = info[i]
        if startnode not in edges:
            edges[startnode] = set()
        edges[startnode].add(endnode)

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

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