将文件元素读入邻接表

Reading file elements into an adjacency list

我有一个文件包含:

0 1 95.21
0 2 43.8
1 3 10.4
2 5 67.1

我正在尝试从中创建一个邻接表。其中前两行表示相互连接的顶点,第三列表示边的长度。我希望 python 产生这样的输出:

[[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],[0,3],[0,5]]

但我想不出包括边长的方法。而不是 [1,2] 我想要

[[[1, 95.21],[2, 43.8]],[[0, 95.21],[3, 10.4]],[[0, 43.8],[5, 67.1]]

希望对此有所帮助。

您应该 append 包含整数和距离的 list 而不是 append 单个整数。

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 的解决方案而不是这种方式,因为它很干净并且适用于这种格式的所有可能输入。

在这个解决方案中,我试图避免提前知道数据中有多少个节点。

>>> 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)])