Corresponding scores based on edges of a graph

2019-02-26 03:50发布

问题:

import numpy as np

score = np.array([
    [0.9, 0.7, 0.2, 0.6, 0.4],
    [0.7, 0.9, 0.6, 0.8, 0.3],
    [0.2, 0.6, 0.9, 0.4, 0.7],
    [0.6, 0.8, 0.4, 0.9, 0.3],
    [0.4, 0.3, 0.7, 0.3, 0.9]])

l2= [(3, 5), (1, 4), (2, 3), (3, 4), (2, 5), (4, 5)]

I want to get the corresponding scores vector based on the edge list.The score array represents an adjacency matrix where score(1,2) represents the edge (1,2)

OUTPUT:

[0.7 0.6 0.6 0.4 0.3 0.3]

回答1:

We could convert the list of tuples holding the indices to array and then use slicing or tuple packed ones.

So, convert to array :

l2_arr = np.asarray(l2)-1

Then, one way would be -

score[l2_arr[:,0], l2_arr[:,1]]

Another -

score[tuple(l2_arr.T)]

For completeness, here's one using a loop-comprehension to extract the row, column indices and thus avoiding any array conversion -

score[[i[0]-1 for i in l2], [i[1]-1 for i in l2]]