从边缘列表创建邻居列表(Python:访问指定第一个值的元组)

Creating list of neighbors from edgelist (Python: accessing tuples with first value specified)

使用 NetworkX,我获得了描述图中边(顶点对)的元组列表:

G = [(1, 2), (1, 3), (1, 4), (2, 4), (3, 8), (4, 5), (8, 15), (5, 6), (5, 7), (6, 17), (7, 11), (7, 15), (7, 16), (17, 12), (11, 12), (11, 13), (15, 9), (15, 10), (16, 9), (9, 18), (18, 13), (18, 14), (10, 14)]

使用这个列表,我想遍历每个顶点,并找到每个相邻的顶点,但我想按顺序执行此操作。所以我想得到的是一个嵌套列表,其中第 i 个子列表包含顶点 i.

的每个邻居
Neighbors = [[2, 3, 4], [1, 4], [1, 8], [1, 2, 5], [4, 6, 7], [5, 17], [5, 11, 15, 16], [3, 15], [15, 16, 18], [14, 15], [7, 12, 13], [11, 17], [11, 18], [10, 18], [7, 8, 9, 10], [7, 9], [6, 12], [9, 13, 14]]

,但也可以是另一种排序数据结构。

但是,由于我的图可能包含一百万条边和顶点,因此我想实现一个不会为每个顶点遍历整个列表的例程,因为我想保持较低的运行时间。

有什么方法可以实现吗?非常感谢任何帮助。

您可以使用 defaultdict 如下:

from collections import defaultdict
d = defaultdict(set)

for x, y in G:
    d[x].add(y)
    d[y].add(x)

d
defaultdict(set,
            {1: {2, 3, 4},
             2: {1, 4},
             3: {1, 8},
             4: {1, 2, 5},
             5: {4, 6, 7},
             6: {5, 17},
             7: {5, 11, 15, 16},
             8: {3, 15},
             9: {15, 16, 18},
             10: {14, 15},
             11: {7, 12, 13},
             12: {11, 17},
             13: {11, 18},
             14: {10, 18},
             15: {7, 8, 9, 10},
             16: {7, 9},
             17: {6, 12},
             18: {9, 13, 14}})

您可以将字典转换为列表:

[sorted(d[k]) for k in range(1, max(d.keys())+1)]
[[2, 3, 4],
 [1, 4],
 [1, 8],
 [1, 2, 5],
 [4, 6, 7],
 [5, 17],
 [5, 11, 15, 16],
 [3, 15],
 [15, 16, 18],
 [14, 15],
 [7, 12, 13],
 [11, 17],
 [11, 18],
 [10, 18],
 [7, 8, 9, 10],
 [7, 9],
 [6, 12],
 [9, 13, 14]]

如果你可以访问原始图g,你可以遍历原始边列表(如果没有,你可以从G构造g):

[list(v.keys()) for _,e in g.edge.items()]
#[[2, 3, 4], [1, 4], [8, 1], [1, 2, 5], [4, 6, 7], [17, 5], [16, 11, 5, 15], ...]

如果您认为 dict_keys 没问题,您可以省略 list(),这只是列表的只读版本:

[v.keys() for _,e in g.edge.items()]
#[dict_keys([2, 3, 4]), dict_keys([1, 4]), dict_keys([8, 1]), ...]