网络X打乱节点顺序。

9

我是一名编程新手,也是新来的这里,你好!

我在使用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
请查看 https://dev59.com/_2Up5IYBdhLWcg3wJU9J 了解更多关于为什么会发生这种情况的信息。NetworkX 使用 Python 字典来存储节点。 - Joel
2个回答

6
您可以按以下方式对输出节点进行排序:
print "G.nodes  = ", sorted(G.nodes())

或者你可以像这样对边进行排序

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

2
如果你只是想用这个来打印,Aric的解决方案就可以了。但是如果你要用邻接矩阵进行计算,并且希望在不同的运行中得到一致的矩阵,你应该使用有序图
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']

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接