【问题标题】:Create an adjacency list in python from csv file从 csv 文件在 python 中创建邻接列表
【发布时间】:2018-09-02 18:36:06
【问题描述】:

我是 python 新手。我有一个显示距离矩阵的 CSV 文件,并且想使用 CSV 中的信息构建一个邻接列表,但我不知道如何执行此任务。

CSV 数据集:

我希望距离是边缘的权重。以下是我的预期结果示例:

AdjList = {1: [{Node2:11242, node5:1511}], 2:[{Node6:1024, Node10:985}], etc. }

【问题讨论】:

    标签: python arrays python-2.7 dictionary


    【解决方案1】:

    不失一般性,下面是通过numpycollections.defaultdict 的解决方案。

    结果是一个嵌套字典,其中外键是行号,内键是列号。

    该解决方案可以适应您的问题和所需的输出。您可能希望查看pandas 以分别提取行号、列名和数据以用于以下算法。

    from collections import defaultdict
    import numpy as np
    
    arr = np.array([[0, 134, 0, 451, 0],
                    [234, 0, 4513, 0, 0],
                    [0, 0, 132, 34, 0],
                    [452, 562, 0, 0, 0]])
    
    d = defaultdict(lambda: defaultdict(int))
    
    for i in range(arr.shape[0]):
        for j in range(arr.shape[1]):
            val = arr[i, j]
            if val != 0:
                d[i+1][j+1] = val
    

    结果

    defaultdict(<function __main__.<lambda>>,
                {1: defaultdict(int, {2: 134, 4: 451}),
                 2: defaultdict(int, {1: 234, 3: 4513}),
                 3: defaultdict(int, {3: 132, 4: 34}),
                 4: defaultdict(int, {1: 452, 2: 562})})
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-12-31
      • 1970-01-01
      • 2015-06-29
      • 1970-01-01
      • 2011-05-06
      • 2010-11-10
      • 2020-11-02
      • 2018-04-25
      相关资源
      最近更新 更多