简体   繁体   English

取矩阵的非零元素的索引

[英]Take indices of non zero elements of matrix

I create matrix "adjacency_matrix" with following code:我使用以下代码创建矩阵“adjacency_matrix”:

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;例如 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”中保存非零元素的行:

li_r = [0 0 1 2 2]

and save columns of non zero element in "li_c":并将非零元素的列保存在“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我的目标是将 (0,0) (0,1) (1,2) (2,0) (2,1) 作为非零元素的行和列,并将它们提供给g.addEdge(u,v)在我的代码中,我的意思是我想要

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.我是 Python 新手,如果可能的话,请帮助我并重写我的代码。

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()它返回一个位置列表 (x,y),您可以遍历每个位置并将它们插入 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() g.addEdge()

for i in pos:
    g.addEdge(*i)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM