gpt4 book ai didi

python - 将文件元素读入邻接表

转载 作者:行者123 更新时间:2023-11-30 22:15:07 25 4
gpt4 key购买 nike

我有一个文件包含:

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

希望得到一些帮助。

最佳答案

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

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

关于python - 将文件元素读入邻接表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50368914/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com