【问题标题】:Shortest paths and dictionary最短路径和字典
【发布时间】:2021-10-20 17:18:45
【问题描述】:

我有以下最短路径

{'A': {'B': ['A', 'B'],
  'A': ['A'],
  'C': ['A', 'C']},
 'D': {'A': ['D', 'A'],
  'B': ['D', 'B'],
  'C': ['D', 'C']}}

如下构建:

selected_shortest = {source: {target: nx.shortest_path(G, source, target) for target in list4path if nx.has_path(G, source, target)} for source in G.nodes()}

其中 G 是一个网络

G = nx.from_pandas_edgelist(edges, source='Node', target='Target')

list4path 是潜在目标的列表(例如,A、B 和 C)。 我想获得它们之间的距离(或间隔),而不是列表中源和目标之间的节点名称。所以,例如,

{'A': {'B': 1,
  'A': 0
  'C': 1},
 'D': {'A': 1,
  'B': 1,
  'C': 1}}

为了取这些计算出的最短路径的平均值。 你能帮我得到这些平均值吗?

【问题讨论】:

  • 似乎你可以将所有列表值设置为 len(list)-1,不是吗?

标签: python networkx shortest-path


【解决方案1】:

我认为您想将 shortest_path 替换为 shortest_path_length

【讨论】:

    【解决方案2】:

    也许这就是你想要的:

    for node in selected_shortest:
      for key in selected_shortest[node]:
        selected_shortest[node][key] = len(selected_shortest[node][key]) - 1 
    

    【讨论】:

    • 嗨 Chaos_Is_Harmony,我收到这个错误:TypeError: object of type 'int' has no len() 当我运行这个时:----> 3 selected_shortest[node][key] = len(selected_shortest[node][key]) - 1。我检查并 selected_shortest 有值。如何可视化 for 循环生成的结果?
    • 所以你是说selected_shortest[node][key] 返回一个int 而不是list?如果是这种情况,您在问题开头的 dicts 并不能准确地表示 selected_shortest 实际上是什么......
    • 添加方括号,它不识别目标。我正在关注这个问题中提出的解决方案:stackoverflow.com/questions/68801210/…
    • 是的,nx.shortest_path() 必须已经返回了一个列表...
    • 鉴于错误信息,我想知道 nx.shortest_path(G, source, target) for target in list4path if nx.has_path(G, source, target) 在某些情况下是否返回一个 ``int``` 而不是 list...?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多