Reputation: 121
The output from networkx's generate_adjlist() module is a bit weird and I am trying to get the adjacency list of my graph in the form of list or numpy array. How to do it? Any tip is appreciated. Thanks.
G = nx.lollipop_graph(4, 3)
for line in nx.generate_adjlist(G):
print(line)
[0]
0 1 2 3
1 2 3
2 3
3 4
4 5
5 6
6
Upvotes: 1
Views: 1052
Reputation: 88226
nx.generate_adjlist
returns a line of the graph, in adjacency list format. You can generate a nested list from the result with:
G = nx.lollipop_graph(4, 3)
np.array(list(nx.generate_adjlist(G)))
# array(['0 1 2 3', '1 2 3', '2 3', '3 4', '4 5', '5 6', '6'], dtype='<U7')
Numpy arrays are suited for homogeneous data structures, i.e. for a list with equally sized inner lists. If you try to build an array from the following, you'll see that you get an array of lists. What you could do is build a nested list from the result with:
list(map(str.split, nx.generate_adjlist(G)))
[['0', '1', '2', '3'],
['1', '2', '3'],
['2', '3'],
['3', '4'],
['4', '5'],
['5', '6'],
['6']]
As per the question mentioned in the comments, we can obtain an enumerated dictionary as (do note that effectively a list would be indexed in the same way though):
dict(enumerate(map(str.split, nx.generate_adjlist(G))))
{0: ['0', '1', '2', '3'],
1: ['1', '2', '3'],
2: ['2', '3'],
3: ['3', '4'],
4: ['4', '5'],
5: ['5', '6'],
6: ['6']}
Upvotes: 1