用Python表示网络 [英] Representing a network in Python
问题描述
我有一个顶点,例如dic = {'a': 0, 'b': 1, 'c': 2, 'd': 3, 'e': 4, 'f': 5, 'n':6, 'm':7, 'g':8}
,并且我有两列,分别表示这些顶点之间的关系:
I have a vertices such as dic = {'a': 0, 'b': 1, 'c': 2, 'd': 3, 'e': 4, 'f': 5, 'n':6, 'm':7, 'g':8}
and i have two columns as follows represent the relationship between the vertices :
a a
b d
e f
c f
n f
m g
我想通过边缘将第一列中的每个顶点与第二列中的对应顶点关联.所以a
和a
代表一个循环. b
和d
都可以. e
,c
和n
共享相同的顶点f
.与其说e
与f
,c
与f
和n
与f
,我们可以说e
,c
和n
与f
.
I want to associate each vertex in the first column with the corresponding vertex in the second column by an edge. So a
with a
is represent a loop. b
with d
is fine. e
,c
and n
they are sharing the same vertex f
. Instead to say e
with f
, c
with f
and n
with f
we can say e
, c
and n
with f
.
推荐答案
请参阅: https://www.python.org/doc/essays/graphs/
graph = {
'a' : [ 'a' ],
'b' : [ 'd' ],
'c' : [ 'f' ],
'd' : [],
'e' : [ 'f' ],
'f' : [],
'g' : [],
'm' : [ 'g' ],
'n' : [ 'f' ]
}
print [ vertex for vertex, edges in graph.items() if 'f' in edges ]
好吧,听起来您只是想要一个函数来根据给定的输入构建图形?
Ok, it sounds like you just want a function to build the graph from your given inputs?
类似这样的东西:
def build_graph( vertices, edges ):
graph = dict( (v, list()) for v in vertices.keys() )
for a, b in edges:
graph[ a ].append( b )
return graph
如果您需要帮助将列数据解析为两元组列表,那么这完全是一个不同的问题
If you need help parsing your columnar data into a list of two-tuples then that's a different question entirely
这篇关于用Python表示网络的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!