Reputation: 35
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.
Upvotes: 0
Views: 119
Reputation: 385930
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)
Upvotes: 1