【问题标题】:NetworkX shuffles nodes orderNetworkX 打乱节点顺序
【发布时间】:2016-06-20 06:56:53
【问题描述】:

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

我在 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']

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

提前致谢!

【问题讨论】:

标签: python python-2.7 graph nodes networkx


【解决方案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']

【讨论】:

    【解决方案2】:

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

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

    或者类似地你可以像这样对边缘进行排序

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-01
      • 1970-01-01
      相关资源
      最近更新 更多