问题
In context of graph algorithms, we are usually given a convenient representation of a graph (usually as an adjacency list or an adjacency matrix) to operate on.
My question is, what is an efficient way to construct an Adjacency list from a given list of all edges?
For the purpose of the question, assume that edges are a list of tuples (as in python) and (a,b) denotes a directed edge from a to b.
回答1:
A combination of itertools.groupby
(docs), sorting and dict
comprehension could get you started:
from itertools import groupby
edges = [(1, 2), (2, 3), (1, 3)]
adj = {k: [v[1] for v in g] for k, g in groupby(sorted(edges), lambda e: e[0])}
# adj: {1: [2, 3], 2: [3]}
This sorts and groups the edges by their source node, and stores a list
of target nodes for each source node. Now you can access all adjacent nodes of 1
via adj[1]
来源:https://stackoverflow.com/questions/36524816/construct-an-adjacency-list-from-a-list-of-edges