简体   繁体   中英

Edge between all nodes in NetworkX Graph

I am able to add an edge between any two individual node like below:

G.add_edge(node1, node)

But if I wanted to and edge between any two nodes (All nodes should be adjacent to each other) it becomes difficult when large number of nodes are taken.

Example: If number are nodes are four and they are 1,2,3,4.The Graph should look like this 在此处输入图片说明

For above graph I am adding nodes as follow:

graph = [(1, 2),(1, 3),(1, 4), (2, 3),(2, 4), (3, 4)]
for edge in graph:
        G.add_edge(edge[0], edge[1])

Is there any default option as parameter in Graph construction for my requirement?

Basically I need to construct a clique for given nodes.

Thanks

From your description I think you're trying to make a complete graph. Networkx has a built in method to create a complete graph.

import networkx as nx
G=nx.complete_graph(4)
G.edges()
>[(0, 1), (0, 2), (0, 3), (1, 2), (1, 3), (2, 3)]

If you don't want the nodes to be named 0,1,2,3 , then you can rename the nodes in G with some other names. Follow the commands above with:

nodenames = ['a', 'b', 'c', 'd']
mapping = {i:nodename for i,nodename in enumerate(nodenames)}
#now mapping looks like {0:'a', 1:'b', ...}
H=nx.relabel_nodes(G,mapping)
H.edges()
> [('a', 'c'), ('a', 'b'), ('a', 'd'), ('c', 'b'), ('c', 'd'), ('b', 'd')]

(note - I'm not a fan of the dict comprehension I used to define mapping - I'd appreciate if anyone can give me a more direct version that doesn't require enumerating).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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