将边列表转换为相邻列表

时间:2019-04-03 01:56:14

标签: python graph

我有这样的边缘列表

In [12]: pre =   [[1,0],[2,0],[3,1],[3,2]] 
In [19]: graph = [[]] * 4                                                                                                     
In [20]: graph                                                                                                                
Out[20]: [[], [], [], []]

将其转换为相邻的列表图:

In [21]: for u, v in pre: 
    ...:     graph[v].append(u) 
    ...:                      

但获得结果

In [22]: graph                                                                                                                
Out[22]: [[1, 2, 3, 3], [1, 2, 3, 3], [1, 2, 3, 3], [1, 2, 3, 3]]

In [25]: for u, v in pre: 
    ...:     graph[v].append(u) 
    ...:     print(graph) 
    ...:                                                                                                                      
[[1], [1], [1], [1]]
[[1, 2], [1, 2], [1, 2], [1, 2]]
[[1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3]]
[[1, 2, 3, 3], [1, 2, 3, 3], [1, 2, 3, 3], [1, 2, 3, 3]]

我想要的结果是

    [[1, 2], [3], [3], []]

我的用法有什么问题?

0 个答案:

没有答案