NetworkX随机播放节点顺序

时间:2016-03-06 19:45:24

标签: python python-2.7 graph nodes networkx

我是编程的初学者,我是新来的,所以你好!

我在networkX中遇到节点顺序问题。 这段代码:

letters = []
G = nx.Graph()
for i in range(nodesNum):
    letter = ascii_lowercase[i]
    letters.append(letter)
    print letters

G.add_nodes_from(letters)
print "G.nodes  = ", (G.nodes())

返回:

['a']
['a', 'b']
['a', 'b', 'c']
['a', 'b', 'c', 'd']
['a', 'b', 'c', 'd', 'e']
['a', 'b', 'c', 'd', 'e', 'f']
['a', 'b', 'c', 'd', 'e', 'f', 'g']
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i']
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']
G.nodes  =  ['a', 'c', 'b', 'e', 'd', 'g', 'f', 'i', 'h', 'j']

虽然我想按正常(按字母顺序)排序。 谁能告诉我我做错了什么? 顺序对我很重要,因为后来我要求用户告诉我边缘在哪里。

提前致谢!

2 个答案:

答案 0 :(得分:4)

您可以像这样对输出中的节点进行排序

print "G.nodes  = ", sorted(G.nodes())

或类似地,您可以像

那样对边缘进行排序
print "G.edges = ", sorted(G.edges())

答案 1 :(得分:1)

如果您只想将此打印用于打印,Aric的解决方案就可以了。但是,如果您要使用相邻矩阵进行计算,并且希望在不同的运行中使用一致的矩阵,you should do

letters = []
G = nx.OrderedGraph()
for i in range(10):
    letter = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'][i]
    letters.append(letter)
    print (letters)

G.add_nodes_from(letters)
print ("G.nodes  = ", (G.nodes()))

返回

['a']
['a', 'b']
['a', 'b', 'c']
['a', 'b', 'c', 'd']
['a', 'b', 'c', 'd', 'e']
['a', 'b', 'c', 'd', 'e', 'f']
['a', 'b', 'c', 'd', 'e', 'f', 'g']
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i']
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']
G.nodes  =  ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']
相关问题