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

标签 python graph 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]]

希望得到一些帮助。

最佳答案

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

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

相关文章:

php - 使用递归 PHP 组织 mySQL 数据

r - 从邻接矩阵、r、igraph 获取传染链

python - 基于 Pandas 中唯一数字的两个 csv 文件之间的日期差异

python Tornado 处理程序 IO 阻塞整个服务器网络

mysql - 邻接列表模型或嵌套集模型,我应该使用哪种数据模型来存储分层数据?

mysql - 将 MYSQL 数据库导入 NeO4j

algorithm - 找到具有 k 个蓝色顶点的树的最佳顶点覆盖

python - 在 python 中从多元 pdf 中采样

python - Numba - 来自 jitted 函数内部的参数(numpy 数组)的内存地址

javascript - 使用与所有主要浏览器兼容的 javascript 创建条形图、折线图和饼图时使用什么?