0

The problem I am facing is following:

Suppose we have some class ( not important what it does):

class Node: ...
    ...

What I need now is creating several instances of this class; all with names. I tried several things, here one try, which is obviously not working. just to make clear what I want to achieve:

for i in range(number_of_instances):
    "name"+str(i+1) = Node()

I need name for all of these objects to put them later on in a list. Actually it's the list containing all the nodes from a graph. The graph will be made with the networkx module. I need to be able to differentiate somehow between the nodes in the list. That's why I need the name.

my_graph = networkx.Graph()
for i in range(number_of_nodes):
    my_graph.add_node(Node(), name = str(i+1))

After executing this, my_graph.nodes() list somehow has mixed up the order of the nodes. So it does not correspond to order in which the nodes have been added to the graph. So I don't know anymore how to exactly differentiate between the nodes.

EDIT

Given the laplacian for the graph I set everything up and then draw the graph.

name_dict = nx.get_node_attributes(my_graph, "name")
pos = nx.spring_layout(my_graph)
nx.draw(my_graph, pos, with_labels=False)
nx.draw_networkx_labels(my_graph, pos, name_dict)
plt.show()

However this does not result in the correct labeling.

nemo
  • 25
  • 1
  • 10
  • Hello. While the use of ``globals()`` to do what you want is frowned upon by many people (I don't know why), I think you'll find the answer to your problem in this response of me here: (http://stackoverflow.com/a/5036827/551449) – eyquem Mar 15 '14 at 12:27
  • `Graph.node` (what `nodes()` returns) is a dictionary... which is implicitly unordered. You can get nodes by node attribute i.e. names though. What exactly are you trying to do? – Corley Brigman Mar 15 '14 at 13:16
  • After this I want to draw the graph. See **edit** but the labels are not correct anymore..-.- – nemo Mar 15 '14 at 13:35
  • @eyquem: the *why* is that it generally makes your code more complex and harder to understand, and the use of globals makes your code harder to manage. – Bryan Oakley Mar 15 '14 at 13:42

1 Answers1

1

You don't need a name, you only need a reference. One simple solution is to put the reference in a dictionary:

node = {}
for i in range(number_of_instances):
    node[i] = Node()
...
for i in range(number_of_nodes):
    my_graph.add_node(node[i], name="node %s" % i)
Bryan Oakley
  • 370,779
  • 53
  • 539
  • 685
  • Thanks. I had troubles to label the reference and not the address where the Node-object is located. My code up there did not print the right reference to the right noe. I guess my code somehow was almost correct. Anyway it works now ^^ – nemo Mar 15 '14 at 14:05