Take indices of non zero elements of matrix

Hi, I create matrix “adjacency_matrix” with following code:

n = int(input()) # Initialize matrix

adjacency_matrix = []

# For user input

for i in range(n):

a =[]

for j in range(n):

a.append(int(input()))

adjacency_matrix.append(a)

I want to save indices of non zero elements of above matrix.

for example n = 3;

adjacency_matrix =

2 3 0

0 0 1

1 5 0

I want to save rows of non zero element in “li_r”:

li_r = [0 0 1 2 2]

I want to save columns of non zero element in “li_c”:

li_c = [0 1 2 0 1]

My Question is: Is this code is true?

for i in range(n):

li_r = [];

li_c = []

for j in range(n):

if adjacency_matrix[i-1][j-1]!=0:

li_r.append(i-1)

li_c.append(j-1)

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.