【发布时间】:2015-10-03 12:05:40
【问题描述】:
您好,我有一个格式如下的文件:
1 5
2 6
3 6
4 5
5 6
5 7
5 8
...
而我想要的是制作这样的字典:
1:5
2:6
3:6
4:5
5: 1, 4, 6, 7, 8
6: 2, 3, 5,
....
该文件是无向图节点之间的连接,我想将其转换为字典,其中节点作为键,该节点的邻居作为值(邻接表)。
我的问题是我不知道如何从文件中检索数据以将节点与他的所有邻居匹配。
我试过了,
nodeList = list()
with open(file) as inputfile:
for line in inputfile.readlines():
nodeList.append(tuple(line.strip().split()))
d = defaultdict(list)
for k, v in nodeList:
d[k].append(v)
结果是一个字典:
[...('5', ['6', '7', '8']),..., ('1', ['5']),.., ('4', ['5']).....]
但这并不完全正确,因为例如我希望 4 和 1 显示为键 5 中的值。
【问题讨论】:
标签: python file python-3.x dictionary graph