Adjacency matrix in Python

后端 未结 4 822
我寻月下人不归
我寻月下人不归 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:16

    I like tupled keys for 2d structures like this in python.

    {(1, 1): 0, (3, 2): 9... }
    

    I think it's conceptually clearest since it drops the intermediary data structure in the above solution. Nonetheless, that intermediary data structure -- the inner list or row / column-- can be useful if you intend to access your structure either row or column wise.

     for x, row in enumerated(matrix, 1):
           # process whole row 
           for y in enumerate(row, 1):
                 # process cell...
    

    If cell-wise data access is your game though, it's hard to beat the following for expressive simplicity:

    for (x, y), value in matrix.iteritems():
          # act on cell
    

    Sort it if you want.

     # (1, 1), (1, 2)...
     for (x, y), value in sorted(matrix.iteritems()):
           # act on cell
    

提交回复
热议问题