Construct an Adjacency List from a List of edges?

℡╲_俬逩灬. 提交于 2019-12-08 07:50:31

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!