简体   繁体   English

使用Dict和List在Python中创建邻接列表

[英]Creating Adjacency List in Python using Dict and List

I wanted to create a data structure that can store the name of a vertex, vertices it is adjacent to along with the edge weight. 我想创建一个数据结构,该结构可以存储顶点的名称,与顶点相邻的顶点以及边缘权重。 I thought of creating a dict that maps a vertex to a list that further has dict to store vertices it is adjacent to with edge weight. 我想到了创建一个将顶点映射到listdict ,该dict还进一步具有存储与边权重相邻的顶点的dict

In other words: 换一种说法:

D = {
    vertex1: [
        {
            Adj_vertex1: edge weight
        }, 
        {
            Adj_vertex2:    edge weight
        } 
    ]
}

Is there an effective way to do this? 有有效的方法吗? Also, if I use the structure above how do I access Adj_vertex2 ? 另外,如果我使用上面的结构,如何访问Adj_vertex2

Dictionary works fine unless you have more complex structure. 除非您具有更复杂的结构,否则词典工作正常。 But you are declaring a list of dictionaries for your vertices. 但是您要声明一个顶点字典列表。 You can simplify it like this; 您可以这样简化它;

D = { vertex1: {Adj_vertex1: edge_weight, Adj_vertex2: edge_weight}}

And get adj_vertex2 weight like this; 并获得adj_vertex2这样的权重;

D[vertex1][Adj_vertex2]

Or if you want to get a default value if a vertex is not adjacent to another, thus not exists in the dictionary you can use this (thanks to Hossein's comment): 或者,如果要获得默认值(如果一个顶点与另一个顶点不相邻,因此在字典中不存在),则可以使用此值(由于侯赛因的评论):

D[vertex1].get(Adj_vertex2, 0)

And add a new vertex like this; 并添加一个这样的新顶点;

D[new_vertex] = {Adj_vertex1: edge_weight, Adj_vertex2: edge_weight}

You can do: 你可以做:

d = {'vertex1': [ {'adj_vertex1': (edge, weight)}, {'adj_vertex2': (edge, weight)}]}

To access adj_vertex2 you must do d['vertex1'][1]['adj_vertex2'] 要访问adj_vertex2您必须执行d['vertex1'][1]['adj_vertex2']

This is not a very good way to work with graphs in python in my opinion. 我认为这不是在python中使用图形的好方法。 You should check some libraries out like python-graph or you could use sets , sets are a good way to use graphs with python as far as I remember. 您应该像python-graph这样检查一些库,或者可以使用set ,据我所知,sets是将图与python一起使用的好方法。

Note: (this, is, a, tuple) . 注意:( (this, is, a, tuple) On tuples . 元组上

One efficient way that uses relatively standard tools would be to store adjacency as a sparse matrix. 使用相对标准的工具的一种有效方法是将邻接存储为稀疏矩阵。 This would require you to use scipy and to number your vertices. 这将要求您使用scipy并对顶点进行编号。

Assume you have the connected vertices as list of lists and the weights as another list of lists of the same structure 假设您具有相连的顶点作为列表列表,权重作为另一个具有相同结构的列表列表

inds = [[1,3], [], [0,2], [0,2,3]]
weights = [[0.1,0.2], [], [1,1], [2,0.5,-0.1]]

adj = sparse.lil_matrix((4,4))
for i, (j, w) in enumerate(zip(inds, weights)):
    adj[i, j] = w

adj
# <4x4 sparse matrix of type '<class 'numpy.float64'>'
        with 7 stored elements in LInked List format>
adj.A # dense representation
# array([[ 0. ,  0.1,  0. ,  0.2],
         [ 0. ,  0. ,  0. ,  0. ],
         [ 1. ,  0. ,  1. ,  0. ],
         [ 2. ,  0. ,  0.5, -0.1]])

adj = adj.tocsr() # convert to more efficient format

# get vertices connected to vertex 3:
adj[3].nonzero()[1]
# array([0, 2, 3], dtype=int32)

# get corresponding weights:
adj[3].data
# array([ 2. ,  0.5, -0.1])

Using a list of tuples to store the adjacencies and the weights makes more sense to me rather than storing it as dict. 使用元组列表存储邻接关系和权重对我而言比将其存储为dict更有意义。 You can store it something like this, 你可以像这样存储它

    d = {
         'v1': [ ('v2',w1), ('v3', w2) ]
         'v2': [ ('v1', w1) ]
         'v3': [ ('v1', w2) ]
        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM