For the given adjacency matrix below:
[[0, 1, 0, 4], [1, 0, 3, 1], [0, 3, 0, 2], [4, 1, 2, 0]]
How would I go about converting it into an adjacency list like below where each tuple is (node,weight)
[[(1, 1), (3, 4)], [(0, 1), (2, 3), (3, 1)], [(1, 3), (3, 2)], [(0, 4), (1, 1), (2, 2)]]
thanks a lot!
CodePudding user response:
Use a double comprehension:
a=[[0, 1, 0, 4], [1, 0, 3, 1], [0, 3, 0, 2], [4, 1, 2, 0]]
print([[(i,x) for i,x in enumerate(y) if x!=0] for y in a])