问题
I have a list as c4_leaves = [56,78,90,112]. I'm trying to create a complete graph using these elements in c4_leaves as nodes. Here's what I've tried;
V_ex = c4_leaves
G_ex = nx.Graph()
G_ex.add_nodes_from(V_ex)
G_ex = nx.complete_graph(4)
for u,v in G_ex.edges():
G_ex[u][v]['distance'] = distance(points33, u, v)
And then the minimum spanning tree of the above graph as :
T_ex= nx.minimum_spanning_tree(G_ex, weight='distance')
F_ex = list(T_ex.edges())
When I draw G_ex, it gives me the correct graph, but when I print details of the minimum spanning tree, it shows that T_ex.nodes() = [0,1,2,3,56,78,90,112].
Can someone show me the mistake I'm doing?
回答1:
Instead of using complete_graph, which generates a new complete graph with other nodes, create the desired graph as follows:
import itertools
import networkx as nx
c4_leaves = [56,78,90,112]
G_ex = nx.Graph()
G_ex.add_nodes_from(c4_leaves)
G_ex.add_edges_from(itertools.combinations(c4_leaves, 2))
In the case of directed graphs use:
G_ex.add_edges_from(itertools.permutations(c4_leaves, 2))
回答2:
The command G_ex = nx.complete_graph(4) creates a complete graph G whose nodes are 0, 1, 2, and 3. You then add more to G, but it has those nodes.
来源:https://stackoverflow.com/questions/52447723/networkx-creating-a-complete-graph-for-a-given-set-of-nodes