Convert Adjacency matrix into edgelist

import numpy as np

#read matrix without head.
a = np.loadtxt('admatrix.txt', delimiter=',', dtype=int)  #set the delimiter as you need
print "a:"
print a
print 'shape:',a.shape[0] ,"*", a.shape[1]

num_nodes = a.shape[0] + a.shape[1]

num_edge = 0
edgeSet = set()

for row in range(a.shape[0]):
    for column in range(a.shape[1]):
        if a.item(row,column) == 1 and (column,row) not in edgeSet: #get rid of repeat edge
            num_edge += 1
            edgeSet.add((row,column))

print '\nnum_edge:', num_edge
print 'edge Set:', edgeSet
print ''
for edge in edgeSet:
    print edge[0] , edge[1]
扫码关注我们
微信号:SRE实战
拒绝背锅 运筹帷幄