Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/xpath/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何从边列表创建邻接列表_Python_Graph - Fatal编程技术网

Python 如何从边列表创建邻接列表

Python 如何从边列表创建邻接列表,python,graph,Python,Graph,我们希望编写一个函数,将给定工作流的步骤分成多个阶段,这样每个阶段中的所有步骤都可以同时运行。函数应该返回一个列表列表,其中每个列表代表一个阶段。每一步都应在尽可能早的阶段进行 precursor_steps = [ ["clean", "build"], ["metadata", "binary"], ["build", "link"], ["link", "binary"], ["clean", "metadata"], ["build", "resources"]

我们希望编写一个函数,将给定工作流的步骤分成多个阶段,这样每个阶段中的所有步骤都可以同时运行。函数应该返回一个列表列表,其中每个列表代表一个阶段。每一步都应在尽可能早的阶段进行

precursor_steps = [
  ["clean", "build"],
  ["metadata", "binary"],
  ["build", "link"],
  ["link", "binary"],
  ["clean", "metadata"],
  ["build", "resources"]
]
[
  ["clean"],
  ["build", "metadata"],
  ["resources", "link"],
  ["binary"]
]
我正试图为上面的图创建邻接列表,但由于我是Python新手,所以无法做到这一点

当边是整数时,我的下面的代码可以很好地工作,但我不能将它用于字符串边

precursor_steps = [["clean", "build"],["metadata", "binary"],["build", "link"],["link", "binary"],["clean", "metadata"],
  ["build", "resources"]] 

#precursor_steps=[[0,1],[1,2],[2,1]]
def rungraph(nums):
    v = 0
    counter = set()
    for src, dest in nums:
        counter.add(src)
        counter.add(dest)
    #print counter
    v = len(counter)
    adj = {s:[] for s in range(v)}
    for p1, p2 in nums:
        print "p1",p1,"p2",p2
        adj[p1] += [p2]
    print "mtx=>",adj

rungraph(precursor_steps) 

欢迎任何建议。

问题在于您的
adj
声明。您希望此词典将每个顶点映射到与其相邻的顶点列表。但是您正在使用数字作为键初始化
adj
(因此,当您的输入图形具有
n
顶点时,您正在初始化
adj
,以将数字
0
保持为
n-1
作为键,每个都映射到空列表)。这在顶点也是数字的情况下有效,如注释掉的示例中所示。但是当节点是字符串时,它会失败,因为字典是用数字初始化的,因此使用语句
adj[p1]+=[p2]
更新值会失败,因为字符串
p1
在字典中不作为键出现

要解决此问题,请将
adj
的初始化更改为:

adj = {s: [] for s in counter}