我有这个具有这个邻接矩阵的文件:
a:g:w:Q:front:Z
0 2 0 9 12 0
2 0 15 2 0 0
0 15 0 7 2 0
9 2 7 0 3 5
12 0 2 3 0 2
0 0 0 5 2 0
从矩阵中,我们可以看到a没有连接到a但是连接到g,Q,front 在python中,我读取文件并将字母表放入单独的列表中,并将数字放入列表列表中。
verticeName=['a','g','w','Q', 'front','z']
adjacency_list=[[0 2 0 9 12 0],[ 2 0 15 2 0 0 ],[0 15 0 7 2 0],[9 2 7 0 3 5 ],[12 0 2 3 0 2],[0 0 0 5 2 0]]
但是我想把它读成dict格式,这样我以后就可以轻松修改它了。如何改变它:
graph = { "a" : ["g","Q","front"],
"g" : ["a", "W","Q"],
"w" : ["g", "Q", "front", ],
"Q" : ["a","g","w","front,"z"],
"front" : ["a", "w","Q","z"],
"z" :["Q"]
}
基本上左边是顶点,右边是它连接的顶点。
答案 0 :(得分:1)
这可能有所帮助:
vertices_names = []
from collections import defaultdict
graph = defaultdict(list)
with open('your_file_name') as f:
for line_num, line in enumerate(f):
line = line.strip()
if line_num == 0:
# set cols names
vertices_names = line.split(':')
else:
for idx, each_number in enumerate(line.split(' ')):
if int(each_number) > 0:
append_to = vertices_names[line_num-1]
append_what = vertices_names[idx]
graph[append_to].append(append_what)
print("graph is:")
for key, value in graph.items():
print(key, ":", value)
对于您的给定输入,上述代码的输出为:
graph is:
w : ['g', 'Q', 'front']
Q : ['a', 'g', 'w', 'front', 'Z']
Z : ['Q', 'front']
front : ['a', 'w', 'Q', 'Z']
g : ['a', 'w', 'Q']
a : ['g', 'Q', 'front']
正如你在评论中提到的那样,每个边缘的重量也都存储了,所以这里是:
vertices_names = []
from collections import defaultdict
graph = defaultdict(list)
with open('data') as f:
for line_num, line in enumerate(f):
line = line.strip()
if line_num == 0:
# set cols names
vertices_names = line.split(':')
else:
for idx, each_number in enumerate(line.split(' ')):
if int(each_number) > 0:
append_to = vertices_names[line_num-1]
append_what = (vertices_names[idx], int(each_number))
graph[append_to].append(append_what)
print("graph is:")
for key, value in graph.items():
print(key, ":", value)
在给定输入上输出此更新代码为:
graph is:
front : [('a', 12), ('w', 2), ('Q', 3), ('Z', 2)]
w : [('g', 15), ('Q', 7), ('front', 2)]
Q : [('a', 9), ('g', 2), ('w', 7), ('front', 3), ('Z', 5)]
a : [('g', 2), ('Q', 9), ('front', 12)]
Z : [('Q', 5), ('front', 2)]
g : [('a', 2), ('w', 15), ('Q', 2)]
答案 1 :(得分:0)
您可以像现在一样阅读姓名:
names = ['a', 'g', 'w', 'Q', 'front', 'z']
然后创建这样的空列表字典:
graph = {}
for name in names:
graph[name] = []
然后只需读取文件并在字典中将顶点添加到正确的列表中,如果存在边缘:
for source in names:
line = read_line_from_file() # Not a real function
costs = [int(x) for x in line.split()]
for i in range(6):
if costs[i]:
graph[source].append(names[i])
我希望我的问题是对的。