简体   繁体   中英

Generating Adjacency List in NetworkX - How to Include Previous Nodes?

According to the NetworkX documentation , the function generate_adjlist() generates an adjacency list shown below:

>>> G = nx.lollipop_graph(4, 3)
>>> for line in nx.generate_adjlist(G):
...     print(line)
0 1 2 3
1 2 3
2 3
3 4
4 5
5 6
6

However, I notice that the adjacency list do not include the nodes that were linked previously. For example, if you look at row three (2 3), it does not include 0 even though at row one (0 1 2 3), 0 links to node 2.

How do I include the previous nodes which were omitted?

This only applies to undirected graphs. By definition in an adjacency list edges that have already been mentioned do not need to be repeated. When creating a graph, if you were to give over a file that had repeating connections, they would simply be ignored as they are redundant. Your option is to create your own function that lists all the nodes, irrespectively of the fact that they were already mentioned. It would look something like this (code shamelessly modified from the original generate_adjlist code):

def generate_adjlist_with_all_edges():
     for s, nbrs in G.adjacency():
        line = str(s) + delimiter
        for t, data in nbrs.items():
                line += str(t) + delimiter
        yield line[: -len(delimiter)]

G = nx.lollipop_graph(4, 3)
for line in generate_adjlist_with_all_edges(G):
    print(line)
> 0 1 2 3
  1 0 2 3
  2 0 1 3
  3 0 1 2 4
  4 5 3
  5 4 6
  6 5

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