【问题标题】:how can i add weight in adjacency list in python?如何在 python 的邻接列表中添加权重?
【发布时间】:2022-01-16 09:27:23
【问题描述】:

我想给邻接列表增加权重。我的代码如下图所示。

 graph = defaultdict(list) 
 U,V = map(int,input().split()) 
 for i in range(V):
     u,v = map(str,input().split())
     graph[u].append(v)
     graph[v].append(u)

我想将 pair 添加到列表中,但我不知道该怎么做。我是 python 新手。 我想接受如下输入: A B 6 其中 B 是目的地,6 是成本

【问题讨论】:

  • 请以可重现的方式提供一些输入数据和预期输出。
  • A -> B -> 6 , 其中 B 是目的地,6 是成本

标签: python python-3.x list python-2.7


【解决方案1】:
you can use 
List of list of list in python
ArrayList of ArrayList of 2-size ArrayList(for node and weight) in java

0-->[[Node1_connected_with_0,weight],[Node2_connected_with_0,weight],...]

1-->[[Node1_connected_with_1,weight],[Node2_connected_with_1,weight],...]

2-->[[Node1_connected_with_2,weight],[Node2_connected_with_2,weight4],...]

.

.
.

[[[N1,w1],[N2,W2],....],[[N3,w3],[N4,w4]]....]



Here if you will see image its something like this in program.

[

[[3,6],[4,3]],

[[1,3]],

[[4,2]],

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

[[2,4],[4,2]]

]

考虑从 1 开始的数组索引

Node 1 is connected with node 3 and 4 with weight 6 and 3 respectively

Node 2 is connected with node 1 with weight  3 

Node 3 is connected with node 4 with weight 2

and so on

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-05
    • 1970-01-01
    • 2014-05-21
    • 2019-10-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多