简体   繁体   English

NetworkX随机排列节点顺序

[英]NetworkX shuffles nodes order

I'm beginner to programming and I'm new here, so hello! 我是编程的初学者,现在是我的新手,所以您好!

I'm having a problem with nodes order in networkX. 我在networkX中的节点顺序有问题。 This code: 这段代码:

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())

returns this: 返回此:

['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']

While I would like to have it in normal (alphabetical) order. 虽然我想按正常(字母顺序)的顺序放置它。 Could anyone tell me what am I doing wrong? 谁能告诉我我在做什么错? The order is important to me, as later I'm asking user to tell me where the edges are. 顺序对我很重要,因为稍后我要让用户告诉我边缘在哪里。

Thanks in advance! 提前致谢!

You can sort the nodes on output like this 您可以像这样对输出上的节点进行排序

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

or similarly you can sort the edges like 或者类似地,您可以像

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

Aric's solution would do fine if you want to use this for printing only. 如果您只想使用Aric的解决方案进行打印,那它就可以了。 However if you are going to use adjacent matrix for calculations and you want consistent matrices in different runs, 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()))

which returns 哪个返回

['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']

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

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