Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/search/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 输入用于scipy图形搜索的图形_Python_Search_Scipy_Graph Theory - Fatal编程技术网

Python 输入用于scipy图形搜索的图形

Python 输入用于scipy图形搜索的图形,python,search,scipy,graph-theory,Python,Search,Scipy,Graph Theory,根据我可以找到的示例,输入图的形式似乎是NxN,其中图的索引对等于该值 那么矩阵呢 G = [ [0,5,2], [3,0,8], [12,7,0] ] 表示2->1的边权重是索引G[1,0]=3的值 如果这是错误的,请解释 我遇到的问题是如何以这种方式有效地输入节点连接,从字典开始,其中键是节点,值是连接节点的数组 {'node1':[node2,weight1],[node3,weight2]}其中边node1->node2=weight1 我可以遍历一个键循环

根据我可以找到的示例,输入图的形式似乎是NxN,其中图的索引对等于该值

那么矩阵呢

G = [ [0,5,2],
      [3,0,8],
      [12,7,0] ]  
表示
2->1
的边权重是索引
G[1,0]=3的值

如果这是错误的,请解释

我遇到的问题是如何以这种方式有效地输入节点连接,从字典开始,其中键是节点,值是连接节点的数组

{'node1':[node2,weight1],[node3,weight2]}
其中边
node1->node2=weight1


我可以遍历一个键循环并生成一个新的
[[node1,node2,weight1],[node1,node3,weight2]]
,但这也不能让我更接近scipy格式。有没有一种简单的方法可以从字典或迭代数组中进行转换?

假设您已经知道图形中的节点数N,并且图形是定向的,您可以这样做:

def create_csgraph_matrix(d, N):
    M = np.zeros((N,N))
    for i in d:
        for l in d[i]:
            j = l[0]
            weight = l[1]
            M[i, j] = weight
    return M
其中
d
是您表格中的字典。例如:

In [38]: d = {0: [[1, 10], [2, 20]], 2: [[1, 15]]}

In [39]: create_csgraph_matrix(d,3)
Out[39]: 
array([[ 0., 10., 20.],
       [ 0.,  0.,  0.],
       [ 0., 15.,  0.]])
请注意,此图中的节点为0,1,2