How to convert an adjacency matrix to an adjacency list with python?

2024/11/18 17:30:01

I have an adjacency matrix like:

[[  0.,  15.,   0.,   7.,  10.,   0.],[ 15.,   0.,   9.,  11.,   0.,   9.],[  0.,   9.,   0.,   0.,  12.,   7.],[  7.,  11.,   0.,   0.,   8.,  14.],[ 10.,   0.,  12.,   8.,   0.,   8.],[  0.,   9.,   7.,  14.,   8.,   0.]]

How can I convert it to an adjacency list like this one down here?

graph = {'1': [{'2':'15'}, {'4':'7'}, {'5':'10'}],
'2': [{'3':'9'}, {'4':'11'}, {'6':'9'}],
'3': [{'5':'12'}, {'6':'7'}],
'4': [{'5':'8'}, {'6':'14'}],
'5': [{'6':'8'}]}

?

Answer

Keep a list of already added edges in a set edges. Those edges are stored in a frozenset, so already added pairs are not replicated.


Then build your graph by enumerating the outer list with a starting index of one, then the inner list also with a starting index of one. Zero valued entries are eliminated with the if condition on values:

from collections import defaultdict
from pprint import pprintl =[[  0.,  15.,   0.,   7.,  10.,   0.],[ 15.,   0.,   9.,  11.,   0.,   9.],[  0.,   9.,   0.,   0.,  12.,   7.],[  7.,  11.,   0.,   0.,   8.,  14.],[ 10.,   0.,  12.,   8.,   0.,   8.],[  0.,   9.,   7.,  14.,   8.,   0.]]    graph = defaultdict(list)
edges = set()for i, v in enumerate(l, 1):for j, u in enumerate(v, 1):if u != 0 and frozenset([i, j]) not in edges:edges.add(frozenset([i, j]))graph[i].append({j: u})pprint(graph)
# {1: [{2: 15.0}, {4: 7.0}, {5: 10.0}],
#  2: [{3: 9.0}, {4: 11.0}, {6: 9.0}],
#  3: [{5: 12.0}, {6: 7.0}],
#  4: [{5: 8.0}, {6: 14.0}],
#  5: [{6: 8.0}]}

Using a defaultdict which takes a list as default value will help build the list-valued dictionary on the fly.

https://en.xdnf.cn/q/120049.html

Related Q&A

how to plot a box plot of a column of a data frame in two groups in matplotlib

I have the following data frame:value total_spend margin1 29493.14 10203.371 27551.22 19003.072 22881.26 15142.681 15254.77 12337.221 11873.95 9424.231 11382.89 8767.83…

Text manipulation to form an equation

a=0.77 ,b=0.2 ,c=0.20, d=0.79 ,z=(c+d), e=(z*a) ,output=(z+e) I have a text file like above. I need a parser logic that will throw an equation like output=(0.20+0.79)+((0.20+0.79)*a) what are some effi…

Python If statement and logical operator issue [duplicate]

This question already has answers here:How to test multiple variables for equality against a single value?(31 answers)Closed 6 years ago.Im trying to create a small python program to emulate rolling a…

How do I replace a specific string in a 2d array?

Im making a program that Identifies if a blank tile exists or not. I already have a code in my 2d array which is arr2 = [[0 0 0 0 0 0 0 0 0 0 0 0 0 0 0][0 0 0 0 0 0 0 0 0 0 0 0 0 0 0][0 0 0 0 0 0 0 0 0…

from _dlib_pybind11 import * ModuleNotFoundError: No module named _dlib_pybind11

I actually working on a face recognition project but getting an error such as: from _dlib_pybind11 import * ModuleNotFoundError: No module named _dlib_pybind11Please help Ill appreciate any bits of hel…

Sudoku with user input

I am trying to write a Sudoku game with user input. So the user can choose what row/column it wants to and what number. I have to import it from a text file and have made a save and load function. I ha…

Move user to a textchannel as soon as he has pressed a button

I have a problem. I would like to move a user from one specific textchannel to another specific textchannel as soon as he has pressed a button. Unfortunately I get an error. class MyView(discord.ui.Vie…

scrape the about page of websites with Python [closed]

Its difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying thi…

Tkinter entry widget execution [duplicate]

This question already exists:Entry widget in tkinterClosed 2 years ago.So I made a simple program however it doesnt seem to work my code is: e = Entry(root, font = 20,borderwidth=5)e.grid(row=1)def cap…

Python Redefine the variable given as a parameter to the function

Hello I am trying to make theme window with tkinter. There is 5 variable for different widgetss color. I will use color dialog for choosing colors but I dont want to define 5 functions. So I think I ca…