我有一个包含以下内容的文件:
https://storage.googleapis.com/[BUCKET_NAME]/[FILE_NAME]
我试图创建一个邻接列表。前两行表示彼此连接的顶点,第三列表示边的长度。我想让python生成一个输出:
0 1 95.21
0 2 43.8
1 3 10.4
2 5 67.1
我设法编写了产生邻接列表的代码:
[[1, 95.21],[2, 43.8]] #starting from 0, 0 connects to 1 of length 95.21, and 0 connects to 2 of length 43.8
[[0, 95.21],[3, 10.4]] #for 1, 1 also connects to 0 of length 95.21, and 1 connects to 3 of length 10.4
[[0, 43.8],[5, 67.1]] #for 2, 2 also connects to 0 of length 43.8, and 2 connects to 5 of length 67.1
给我
filename2 = open("list.txt", "r", encoding = "utf-8")
efile = filename2
adjList = [0] * 10
for i in range(10):
adjList[i] = []
for line in efile:
edgeEndpoints = line.split()
adjList[int(edgeEndpoints[0])].append(int(edgeEndpoints[1]))
adjList[int(edgeEndpoints[1])].append(int(edgeEndpoints[0]))
print(adjList)
但我无法想出包括边长的方法。而不是[1,2]我想要
[[1,2],[0,3],[0,5]]
希望得到一些帮助。
答案 0 :(得分:2)
在此解决方案中,我试图避免事先知道数据中有多少节点。
>>> from collections import defaultdict
>>> adj_list = defaultdict(set)
>>> with open('list.txt') as f:
for line in f:
start,end,length = line.rstrip().split()
adj_list[int(start)].add((int(end),float(length)))
adj_list[int(end)].add((int(start),float(length)))
这给出了以下结果
>>> for k,v in adj_list.items():
print(k,":",v)
0 : set([(2, 43.8), (1, 95.21)])
1 : set([(3, 10.4), (0, 95.21)])
2 : set([(0, 43.8), (5, 67.1)])
3 : set([(1, 10.4)])
5 : set([(2, 67.1)])
答案 1 :(得分:1)
而不是append
一个整数,你应该append
一个包含整数和距离的list
。
filename2 = open("list.txt", "r", encoding = "utf-8")
efile = filename2
adjList = [0] * 10
for i in range(10):
adjList[i] = []
for line in efile:
edgeEndpoints = line.split()
adjList[int(edgeEndpoints[0])].append([int(edgeEndpoints[1]), float(edgeEndpoints[2])])
adjList[int(edgeEndpoints[1])].append([int(edgeEndpoints[0]), float(edgeEndpoints[2])])
print(adjList)
给出输出:
$ python3 adjtest.py
[[[1, 95.21], [2, 43.8]], [[0, 95.21], [3, 10.4]], [[0, 43.8], [5, 67.1]], [[1, 10.4]], [], [[2, 67.1]], [], [], [], []]
然而,我会选择@ BoarGules的解决方案,而不是这种方式,因为它干净且适用于此格式的所有可能输入。