如何创建关联矩阵

The*_*ior 1 python matrix

我正在尝试创建

[[ 1,  1,  1,  0,  0,  0,  0,  0,  0],
 [-1,  0,  0,  1,  1,  0,  0,  0,  0],
 [ 0, -1,  0, -1,  0,  1,  1,  0,  0],
 [ 0,  0,  0,  0, -1, -1,  0,  1,  0],
 [ 0,  0, -1,  0,  0,  0, -1,  0,  1],
 [ 0,  0,  0,  0,  0,  0,  0, -1, -1]]

S=[1, 2, 3, 4, 5, 6]
D=[[1, 2], [1, 3], [1, 5], [2, 3], [2, 4], [3, 4], [3, 5], [4, 6], [5, 6]]
INC = [[0]*len(D) for _ in range(len(S))]

for i in range(len(D)):
Run Code Online (Sandbox Code Playgroud)

在此之后,我在得到零矩阵的地方做错了

    for j in S:
        if i == j:
            INC.append(1)
Run Code Online (Sandbox Code Playgroud)

我曾尝试将 D 吐到两个不同的列表中,但对我来说它开始变得复杂

my_list1 = [i[0] for i in D]
my_list2 = [i[1] for i in D]
Run Code Online (Sandbox Code Playgroud)

Nic*_*k T 5

我对你想要什么的最好猜测......你的变量名很差。我会使用NetworkX ( networkx)并让它做所有的数学运算。

import networkx as nx

nodes = [1, 2, 3, 4, 5, 6]
edges = [[1, 2], [1, 3], [1, 5], [2, 3], [2, 4], [3, 4], [3, 5], [4, 6], [5, 6]]

G = nx.DiGraph()
G.add_nodes_from(nodes)
G.add_edges_from(edges)

incidence_matrix = -nx.incidence_matrix(G, oriented=True) 
# ^ this returns a scipy sparse matrix, can convert into the full array as below
# (as long as your node count is reasonable: this'll have that squared elements)
print(incidence_matrix.toarray())
Run Code Online (Sandbox Code Playgroud)

输出:

[[ 1.  1.  1.  0.  0.  0.  0.  0.  0.]
 [-1.  0.  0.  1.  1.  0.  0.  0.  0.]
 [ 0. -1.  0. -1.  0.  1.  1.  0.  0.]
 [ 0.  0.  0.  0. -1. -1.  0.  1.  0.]
 [ 0.  0. -1.  0.  0.  0. -1.  0.  1.]
 [ 0.  0.  0.  0.  0.  0.  0. -1. -1.]]
Run Code Online (Sandbox Code Playgroud)