I create matrix "adjacency_matrix" with following code:
n = int(input())
# Initialize matrix
adjacency_matrix = []
# For user input
for i in range(ROWS):
a =[]
for j in range(COLUMNS):
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]
and save columns of non zero element in "li_c":
li_c = [0 1 2 0 1]
My goal is take (0,0) (0,1) (1,2) (2,0) (2,1) as row and column of non-zero element and give them to g.addEdge(u,v) in my code, I mean I want to have
g.addEdge(0,0)
g.addEdge(0,1)
g.addEdge(1,2)
g.addEdge(2,0)
g.addEdge(2,1)
I write this code, but not work:
for i in range(n):
li_r = [];
li_c = []
for j in range(n):
if adjacency_matrix[i][j]!=0:
li_r.append(i)
li_c.append(j)
for i in range(len(li_r)):
for j in range(len(li_c)):
g.addEdge(li_r[i], li_c[j])
I new in Python and if possible, help me and rewrite my code.
Try this list comprehension. It returns a list of positions (x,y) and you can iterate over each one and insert them into g.addEdge()
adjacency_matrix =[[2,3,0],[0,0,1],[1,5,0]]
pos = [(count1, count2) for count1, lst in enumerate(adjacency_matrix) for count2, num in enumerate(lst) if num != 0]
output
[(0, 0), (0, 1), (1, 2), (2, 0), (2, 1)]
g.addEdge()
for i in pos:
g.addEdge(*i)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.