Adjacency matrix in Python

后端 未结 4 755
我寻月下人不归
我寻月下人不归 2021-02-06 03:43

I cannot find any clear explanation as to how to create an adjacency matrix in Python, with weights taken into consideration. I assume it should be relatively simple to create.<

4条回答
  •  醉酒成梦
    2021-02-06 04:28

    I think the most common and simplest concept to store an adjacency matrix is to use a 2D array, which in python corresponds to nested lists

    mat = [[0, 15, 0, 7, 10, 0], [15, 0, ...], [...], [...]]
    m[0][1]  # = 15 (weight of 1-2)
    

    If the values are read only, you can use nested tuples, instead :)

    Of course you can go as crazy as you want with that and use dictionaries or write a class and redefine __getattr__ to be more efficient on access times and storage as the matrix is symmetrical.

提交回复
热议问题