I'm new to python 3 and for further processing I currently have to transform a directed weighted graph (e.g. A->B weight 20, B -> A weight 10) stored as a matrix to single relationship statements like [A,B,20] (node, node, weight).
The matrix looks like this:
matrix A B C
A 0 10 0
B 20 0 5
C 10 5 0
The result I want to get is the following:
[A, B, 10], [B, A, 20], [B, C, 5], [C, A, 10], [C, B, 5]
Is there a simple solution in python to this? Maybe with some libraries to help.
The data lies in a .csv and I would read them in to my program. All I can think of as a solution is to go through each row and write all these statements in some nasty nested while and for mess.
Thx, mx
Just create a loop for rows and another for columns:
table = [[0 , 10 , 0],[20 , 0 , 5],[10 , 5 , 0]]
r = []
l = ['A','B','C']
for i in range(len(['A','B','C'])):
for j in range(len(['A','B','C'])):
if i!=j:
r.append([l[i],l[j],table[i][j]])
print(r)
, the result is this:
[['A', 'B', 10], ['A', 'C', 0], ['B', 'A', 20], ['B', 'C', 5], ['C', 'A', 10], ['C', 'B', 5]]