将矩阵形式的图形转换为字典

时间:2015-04-22 22:31:01

标签: python dictionary matrix graph-theory

假设我有一个布尔矩阵:(像这样):

X   0  1  2  3 
0   1, 1, 1, 1
1   1, 1, 1, 0
2   1, 1, 1, 1
3   1, 0, 1, 1 

我希望在图表中对其进行转换,以便找到两个顶点之间的最短路径(我将应用Dijkstra算法)。我想我已经知道如何在python中应用这个算法,我唯一的问题是在字典中转换这个矩阵,看起来像这样:

graph = {0 : {0:1, 1:1, 2:1, 3:1},
1 : {0:1, 1:1, 2:1},
2 : {0:1, 1:1, 2:1, 3:1},
3 : {0:1, 2:1, 3:1}}
好吧,我不确定我的想法是否正确,有人可以帮助我吗?

1 个答案:

答案 0 :(得分:0)

您可以在问题中创建字典,也可以创建列表列表

$ rails console
> User.find(2)
ActiveRecord::RecordNotFound: Couldn't find User with 'id'=2
> replacer = User.find(5)
=> #<User id: 5, created_at: [omitted for brevity ...] >
replacer.id = 2
=> 2
replacer.save
=> true
> User.find(2)
ActiveRecord::RecordNotFound: Couldn't find User with 'id'=2
> User.find(5)
ActiveRecord::RecordNotFound: Couldn't find User with 'id'=5
> replacer
=> #<User id: 2, created_at: [omitted for brevity ...] >
> replacer.valid?
=> true

为了方便起见,强烈建议使用numpy库(link预构建的Windows安装程序)来操作python中的矩阵。下面会将包含你的数据的文件读成一个numpy矩阵,因为我相信你在问(如果我错了,请纠正我)。

graph = [
    [1, 1, 1, 1],
    [1, 1, 1, 0],
    [1, 1, 1, 1],
    [1, 0, 1, 1]
]

如果在给定示例矩阵的情况下调用import numpy as np with open("matrix.txt") as f: data = np.genfromtxt((line[3:] for line in f), delimiter=',', skiprows=1) ,则输出以下内容:

print data

您会注意到我使用了3的硬编码值来删除第一列 - 因为我没有您的实际数据我不知道这是否准确或不,因为我不知道大行值的大小。您可能希望使用[[ 1. 1. 1. 1.] [ 1. 1. 1. 0.] [ 1. 1. 1. 1.] [ 1. 0. 1. 1.]] 来查找第一个空格的位置,而不是更强大。

然后,您可以对数据执行numpy矩阵operations