graphlib
— 采用像图形结构的操作功能
¶
源代码: Lib/graphlib.py
- class graphlib. TopologicalSorter ( graph = None ) ¶
-
Provides functionality to topologically sort a graph of hashable 节点。
A topological order is a linear ordering of the vertices in a graph such that for every directed edge u -> v from vertex u to vertex v, vertex u comes before vertex v in the ordering. For instance, the vertices of the graph may represent tasks to be performed, and the edges may represent constraints that one task must be performed before another; in this example, a topological ordering is just a valid sequence for the tasks. A complete topological ordering is possible if and only if the graph has no directed cycles, that is, if it is a directed acyclic graph.
若可选 graph argument is provided it must be a dictionary representing a directed acyclic graph where the keys are nodes and the values are iterables of all predecessors of that node in the graph (the nodes that have edges that point to the value in the key). Additional nodes can be added to the graph using the
add()方法。In the general case, the steps required to perform the sorting of a given graph are as follows:
-
创建实例化的
TopologicalSorterwith an optional initial graph. -
Add additional nodes to the graph.
-
调用
prepare()on the graph. -
While
is_active()isTrue, iterate over the nodes returned byget_ready()and process them. Calldone()on each node as it finishes processing.
In case just an immediate sorting of the nodes in the graph is required and no parallelism is involved, the convenience method
TopologicalSorter.static_order()can be used directly:>>> graph = {"D": {"B", "C"}, "C": {"A"}, "B": {"A"}} >>> ts = TopologicalSorter(graph) >>> tuple(ts.static_order()) ('A', 'C', 'B', 'D')
-